Unless specified otherwise, use IPython sessions for each exercise.
4.1 (Discussion: else
Clause) In the script of Fig4.1. , we did not include an else
clause in the if
…elif
statement. What are the possible consequences of this choice?
4.2 (Discussion: Function-Call Stack) What happens if you keep pushing onto a stack, without enough popping?
4.3 (What’s Wrong with This Code?) What is wrong with the following cube
function’s definition?
def cube(x):
"""Calculate the cube of x."""
x ** 3
print('The cube of 2 is', cube(2))
4.4 (What’s Does This Code Do?) What does the following mystery
function do? Assume you pass the list [1,
2,
3,
4,
5]
as an argument.
def mystery(x):
y = 0
for value in x:
y += value ** 2
return y
4.5 (Fill in the Missing Code?) Replace the ***s in the seconds_since_midnight function so that it returns the number of seconds since midnight. The function should receive three integers representing the current time of day. Assume that the hour is a value from 0
(midnight) through 23
(11 PM) and that the minute and second are values from 0
to 59
. Test your function with actual times. For example, if you call the function for 1:30:45 PM by passing 13
, 30
and 45
, the function should return 48645
.
def seconds_since_midnight(***):
hour_in_seconds = ***
minute_in_seconds = ***
return ***
4.6 (Modified average
Function) The average
function we defined in Section 4.11 can receive any number of arguments. If you call it with no arguments, however, the function causes a ZeroDivisionError
. Reimplement average
to receive one required argument and the arbitrary argument list argument *args
, and update its calculation accordingly. Test your function. The function will always require at least one argument, so you’ll no longer be able to get a ZeroDivisionError
. When you call average
with no arguments, Python should issue a TypeError
indicating "average()
missing
1
required
positional
argument."
4.7 (Date and Time) Python’s datetime
module contains a datetime
type with a method today
that returns the current date and time as a datetime
object. Write a parameterless date_and_time
function containing the following statement, then call that function to display the current date and time:
print(datetime.datetime.today())
On our system, the date and time display in the following format:
2018-06-08 13:04:19.214180
4.8 (Rounding Numbers) Investigate built-in function round
at
https://docs.python.org/3/library/functions.html#round
then use it to round the float
value 13.56449
to the nearest integer, tenths, hundredths and thousandths positions.
4.9 (Temperature Conversion) Implement a fahrenheit
function that returns the Fahrenheit equivalent of a Celsius temperature. Use the following formula:
F = (9 / 5) * C + 32
Use this function to print a chart showing the Fahrenheit equivalents of all Celsius temperatures in the range 0–100 degrees. Use one digit of precision for the results. Print the outputs in a neat tabular format.
4.10 (Guess the Number) Write a script that plays “guess the number.” Choose the number to be guessed by selecting a random integer in the range 1 to 1000. Do not reveal this number to the user. Display the prompt "Guess
my
number
between
1
and
1000
with
the
fewest
guesses:"
. The player inputs a first guess. If the guess is incorrect, display "Too
high.
Try
again."
or "Too
low.
Try
again."
as appropriate to help the player “zero in” on the correct answer, then prompt the user for the next guess. When the user enters the correct answer, display "Congratulations.
You
guessed
the
number!"
, and allow the user to choose whether to play again.
4.11 (Guess-the-Number Modification) Modify the previous exercise to count the number of guesses the player makes. If the number is 10 or fewer, display "Either
you
know
the
secret
or
you
got
lucky!"
If the player makes more than 10 guesses, display "You
should
be
able
to
do
better!"
Why should it take no more than 10 guesses? Well, with each “good guess,” the player should be able to eliminate half of the numbers, then half of the remaining numbers, and so on. Doing this 10 times narrows down the possibilities to a single number. This kind of “halving” appears in many computer science applications. For example, in the “Computer Science Thinking: Recursion, Searching, Sorting and Big O” chapter, we’ll present the high-speed binary search and merge sort algorithms, and you’ll attempt the quicksort exercise—each of these cleverly uses halving to achieve high performance.
4.12 (Simulation: The Tortoise and the Hare) In this problem, you’ll re-create the classic race of the tortoise and the hare. You’ll use random-number generation to develop a simulation of this memorable event.
Our contenders begin the race at square 1 of 70 squares. Each square represents a position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground.
A clock ticks once per second. With each tick of the clock, your application should adjust the position of the animals according to the rules in the table below. Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70). Start each animal at position 1 (the “starting gate”). If an animal slips left before square 1, move it back to square 1.
Create two functions that generate the percentages in the table for the tortoise and the hare, respectively, by producing a random integer i in the range 1 ≤ i ≤ 10. In the function for the tortoise, perform a “fast plod” when 1 ≤ i ≤ 5, a “slip” when 6 ≤ i ≤ 7 or a “slow plod” when 8 ≤ i ≤ 10. Use a similar technique in the function for the hare.
Begin the race by displaying
BANG !!!!!
AND THEY'RE OFF !!!!!
Then, for each tick of the clock (i.e., each iteration of a loop), display a 70-position line showing the letter "T"
in the position of the tortoise and the letter "H"
in the position of the hare. Occasionally, the contenders will land on the same square. In this case, the tortoise bites the hare, and your application should display "OUCH!!!"
at that position. All positions other than the "T"
, the "H"
or the "OUCH!!!"
(in case of a tie) should be blank.
After each line is displayed, test for whether either animal has reached or passed square 70. If so, display the winner and terminate the simulation. If the tortoise wins, display TORTOISE
WINS!!!
YAY!!!
If the hare wins, display Hare
wins.
Yuch.
If both animals win on the same tick of the clock, you may want to favor the tortoise (the “underdog”), or you may want to display "It's
a
tie"
. If neither animal wins, perform the loop again to simulate the next tick of the clock. When you’re ready to run your application, assemble a group of fans to watch the race. You’ll be amazed at how involved your audience gets!
4.13 (Arbitrary Argument List) Calculate the product of a series of integers that are passed to the function product
, which receives an arbitrary argument list. Test your function with several calls, each with a different number of arguments.
4.14 (Computer-Assisted Instruction) Computer-assisted instruction (CAI) refers to the use of computers in education. Write a script to help an elementary school student learn multiplication. Create a function that randomly generates and returns a tuple of two positive one-digit integers. Use that function’s result in your script to prompt the user with a question, such as
How much is 6 times 7?
For a correct answer, display the message "Very
good!"
and ask another multiplication question. For an incorrect answer, display the message "No.
Please
try
again."
and let the student try the same question repeatedly until the student finally gets it right.
4.15 (Computer-Assisted Instruction: Reducing Student Fatigue) Varying the computer’s responses can help hold the student’s attention. Modify the previous exercise so that various comments are displayed for each answer. Possible responses to a correct answer should include 'Very
good!'
, 'Nice
work!'
and 'Keep
up
the
good
work!'
Possible responses to an incorrect answer should include 'No.
Please
try
again.'
, 'Wrong.
Try
once
more.'
and 'No.
Keep
trying.'
Choose a number from 1 to 3, then use that value to select one of the three appropriate responses to each correct or incorrect answer.
4.16 (Computer-Assisted Instruction: Difficulty Levels) Modify the previous exercise to allow the user to enter a difficulty level. At a difficulty level of 1, the program should use only single-digit numbers in the problems and at a difficulty level of 2, numbers as large as two digits.
4.17 (Computer-Assisted Instruction: Varying the Types of Problems) Modify the previous exercise to allow the user to pick a type of arithmetic problem to study—1
means addition problems only, 2
means subtraction problems only, 3
means multiplication problems only, 4
means division problems only (avoid dividing by 0) and 5
means a random mixture of all these types.
4.18 (Functional-Style Programming: Internal vs. External Iteration) Why is internal iteration preferable to external iteration in functional-style programming?
4.19 (Functional-Style Programming: What vs. How) Why is programming that emphasizes “what” preferable to programming that emphasizes “how”? What is it that makes “what” programming feasible?
4.20 (Intro to Data Science: Population Variance vs. Sample Variance) We mentioned in the Intro to Data Science section that there’s a slight difference between the way the statistics
module’s functions calculate the population variance and the sample variance. The same is true for the population standard deviation and the sample standard deviation. Research the reason for these differences.
18.220.126.5