StructuringState Answers
StructuringState Answers
StructuringState Answers
Self-Review Questions
Self-review 4.1 What are the values of the variables a, b, c and d after the following
statements have been executed?
a=1
b=2
c=a+b
d=a+c
Self-review 4.2 How many elements are in the dictionary someData after the fol-
lowing code has been executed?
someData = { }
someData[’cheese’] = ’dairy’
someData[’Cheese’] = ’dairy’
Self-review 4.5 Explain why the code in the previous question did not display 10.
Because the scope of the line a = 10 is the method f, which is never called.
Self-review 4.6 Referring to the coffee/cola vending machine state transition dia-
gram (page ??), what happens if the consumer puts three tokens
into the machine without pressing any buttons?
Self-review 4.7 Which of the following are types mutable and which are immutable:
int, list, float, tuple, str.
All the types listed are mutable except for tuple and str.
Self-review 4.8 What happens when the following statement is executed as the
first statement of a program?
x , y , z = 1 , 2 , x ** 3
There is an error – the exception NameError is raised. All the expressions on the
right-hand side are evaluated before any assignments are done so x is being used
before it is assigned.
Self-review 4.9 For each of the following lines, using substitution, hand-evaluate
the following sequence:
x,y,z=1,2,3
z,y,x=x,z,y
x,y,z=(z+1),(x-2),(y*3)
y , z , x = ( y / x ) , ( x * y ) , ( z ** x )
Self-review 4.11 Draw a state transition diagram for a two-bit binary counter. A
binary counter is a digital circuit that has a clock input and an out-
put that gives the number of clock cycles that have been counted.
A two-bit binary counter only has two output connections, which
can have the value of either 1 or 0. This means that a two-bit
counter can count from 0 to 22 − 1 and back to 0 again.
Programming Exercises 29
Self-review 4.12 Draw a state transition diagram for a PIN (Personal Identification
Number) recognizer. If the user enters ‘1’ followed by ‘8’ followed
by ‘5’ followed by ‘0’ followed by ‘enter’, the machine should en-
ter a state called ‘accept’. If the user enters any other combination
of numbers, followed by ‘enter’ the machine should enter a state
called ‘reject’. Is this program a lexer?
Self-review 4.14 What are the types of variables a and b in the following code:
a=(1)
b=(1,)
Self-review 4.15 What is the types and value of y after executing the following
code:
x=[1,2,3,4,5]
y=x[:]
Both x and y are lists. They have the same value, which is [1, 2, 3, 4, 5].
Programming Exercises
1. Try running this small program. What are the values of a and b
after the swap?
2. Why is the result not a having the value 20 and b having the
value 10 as appears to be the intention from the use of the word
swap in the code?
3. Modify the code so that the final result is a having the value 20
and b having the value 1 using simultaneous assignment to swap
the values.
4. Many languages, such as C, C++, Java, do not have simulta-
neous assignment. Modify the program so that it successfully
swaps the two values without using simultaneous assignment.
30 Structuring State
Exercise 4.2 This question is based on a function for stepping through a represen-
tation of a pack of cards. The exact nature of the cards isn’t important.
We use a list to represent pack and in our example we use numbers
between 1 and 5 as cards. They could equally be numbers and suits as
tuples, strings of character names, etc. Here’s the function:
# A hand of cards
cards = [ 1 , 5 , 3 , 4 , 2 , 3 , 2 ]
Exercise 4.3 Write a program to create a frequency table using a dictionary from
a set of input values. The program should repeatedly asks the user
for an input. The input could be anything at all. As each input is
gathered, see if it exists as a key in the dictionary. If it does not exist,
associate the input as a key with the number 1. If it does exist, add
one to the value already associated with it and add it back to the
dictionary. If the value associated with this key is now greater than
or equal to 3, print a message that looks something like “Dear user,
you have entered the word ‘discombobulated’ 3 times!”
Programming Exercises 31
Frequency tables such as this are often used for storing histogram
data. We will look at actually drawing histograms later (Chapter ??).
Frequency tables are also used in some sorting algorithms.
Hint: You will need an infinite loop and to use the raw_input function.
def frequency ( ) :
d={}
while True :
user = raw_input ( ’Please enter the next value or QUIT to finish: ’ )
if user == ’QUIT’ : return
elif d.has_key ( user ) :
d[user] += 1
if d[user] > 2 : print ’Dear user, you have entered the value’, user, d[user], ’times!’
else :
d[user] = 1
Exercise 4.4 Write the Python program that manages the state of the two-bit binary
counter from Self-review 4.11
Exercise 4.5 The lexer in Section ?? can only recognize non-negative integers. Im-
prove the program by adding code to deal with negative numbers.
Exercise 4.6 Create a program for storing a week’s worth of rainfall data. Use a list
to store each day’s value, entered sequentially by the user. When an
entire week has been input, display the days with the minimum and
maximum rainfall.
import math
def rainfall ( ) :
days = [ ’Mon’ , ’Tue’ , ’Wed’ , ’Thu’ , ’Fri’ , ’Sat’ , ’Sun’ ]
rain = [ ]
for i in range ( 7 ) :
r = input ( ’Please enter the rainfall for ’ + days[i] + ’: ’ )
rain.append ( r )
minimum = rain[0]
32 Structuring State
maximum = rain[0]
for i in rain :
if i < minimum : minimum = i
if i > maximum : maximum = i
print ’Min rainfall for this week:’ , minimum
print ’Max rainfall for this week:’ , maximum
for i in range ( len ( rain ) ) :
print ’Rainfall for’ , days[i] , ’=’ , rain[i]
if __name__ == ’__main__’ :
rainfall ( )
Exercise 4.7 Extend your answer to the previous exercise so that it also displays the
mean and standard deviation of the values. The mean is the sum of all
the values divided by the number of values. The standard deviation
is the square root of the sum of the squares of the difference between
each value and the mean, divided by the number of items.
import math
def rainfall ( ) :
days = [ ’Mon’ , ’Tue’ , ’Wed’ , ’Thu’ , ’Fri’ , ’Sat’ , ’Sun’ ]
rain = [ ]
for i in range ( 7 ) :
r = input ( ’Please enter the rainfall for ’ + days[i] + ’: ’ )
rain.append ( r )
# Minimum and Maximum
minimum = rain[0]
maximum = rain[0]
for i in rain :
if i < minimum : minimum = i
if i > maximum : maximum = i
mean = sum ( rain ) / len ( rain )
sd = math.sqrt ( sum ( [ ( x - mean ) ** 2 for x in rain ] ) / ( len ( rain ) - 1 ) )
# Print everything to the console
print ’Min rainfall for this week:’ , minimum
print ’Max rainfall for this week:’ , maximum
print ’Mean rainfall for this week:’ , mean
print ’Standard deviation rainfall for this week:’ , sd
for i in range ( len ( rain ) ) :
print ’Rainfall for’ , days[i] , ’=’ , rain[i]
if __name__ == ’__main__’ :
rainfall ( )
Exercise 4.8 Calculating statistics such as maximum, minimum, mean and stan-
dard deviation is a common task. Now that you have a program to
do it, package the code up into a function that can be used again in
future.
Exercise 4.9 A “wobbly” number is one in which the digits alternate between being
higher and lower than the preceding one. Here are some wobbly
numbers: 19284756242, 90909, 0909. Using what you have learned
Challenges 33
Exercise 4.10 The following code was written before the programmer had drunk
their morning coffee, i.e. they were not properly awake at the time.
It is supposed to add 3% to all the values in the variable salary_scale.
However, there is one very important bug in this code. Find and fix
the bug to make sure everyone gets their 3% pay rise!
salaryScale = ( 20000 , 21500 , 23000 , 24500 , 26000 , 27500 , 29000 )
for i in range ( len ( salaryScale ) ) :
salaryScale[i] += salaryScale[i] * 0.03
print salaryScale
write a function to sort the list – i.e. your function should return the
list:
[ 1 , 2 , 6 , 22 , 43 , 54 , 78 , 99 ]
You can use any method you like to sort the list. Good answers to
this problem will work on any list, not just the one we’ve given here.
Challenges
Challenge 4.1 Imagine a fictional land where monetary units aren’t based on dec-
imal orders. In this land, we have 3 basic units of currency:
Challenge 4.2 Referring back to Exercise 4.2, write a program that uses two hands
of cards (two lists) to play a simple game of “snap”. No cards change
hands, but when two identical cards are played, a message should
be printed.