Ch01 Solutions
Ch01 Solutions
Ch01 Solutions
Algorithms in Python
Michael T. Goodrich
Department of Computer Science
University of California, Irvine
Roberto Tamassia
Department of Computer Science
Brown University
Michael H. Goldwasser
Department of Mathematics and Computer Science
Saint Louis University
1 Python Primer
Creativity
C-1.13) Hint The Python function does not need to be passed the value of
n as an argument.
C-1.14) Hint Note that both numbers in the pair must be odd.
C-1.14) Solution
3
print('\n'.join(reversed(lines)))
4 Chapter 1. Python Primer
C-1.22) Hint Go back to the definition of dot product and write a for loop
that matches it.
C-1.22) Solution
return [a[k]∗b[k] for k in range(n)]
C-1.23) Hint Use a try-except structure.
C-1.23) Solution
try:
data[k] = val
except IndexError:
print("Don't try buffer overflow attacks in Python!")
C-1.24) Hint You can use the condition ch in 'aeiou' to test if a char-
acter is a vowel.
C-1.24) Solution
def num vowels(text):
total = 0
for ch in text.lower( ):
if ch in 'aeiou':
total += 1
return total
C-1.25) Hint Consider each character one at a time.
C-1.26) Hint Try a case analysis for each pair of integers and an operator.
C-1.27) Hint Either buffer the bigger value from each pair of factors, or
repeat the loop in reverse to avoid the buffer.
C-1.27) Solution
def factors(n): # generator that computes factors
buffer = [ ]
k=1
while k ∗ k < n: # while k < sqrt(n)
if n % k == 0:
yield k
buffer.append(n // k)
k += 1
if k ∗ k == n: # special case if n is perfect square
yield k
for val in reversed(buffer):
yield val
5
C-1.28) Hint Use the ∗∗ operator to compute powers.
C-1.28) Solution
def norm(v, p=2):
temp = sum(val∗∗p for val in v)
return temp ∗∗ (1/p)
Projects
P-1.29) Hint There are many solutions. If you know about recursion, the
easiest solution uses this technique. Otherwise, consider using a list to
hold solutions. If this still seems to hard, then consider using six nested
loops (but avoid repeating characters and make sure you allow all string
lengths).
P-1.29) Solution Here is a possible solution:
def permute(bag, permutation):
# When the bag is empty, a full permutation exists
if len(bag) == 0:
print(''.join(permutation))
else:
# For each element left in the bag
for k in range(len(bag)):
# Take the element out of the bag and put it at the end of the permutation
permutation.append(bag.pop(k))
# Take the element off the permutation and put it back in the bag
bag.insert(k, permutation.pop( ))
permute(list('catdog'), [ ])
P-1.30) Hint This is the same as the logarithm, but you can use recursion
here rather than calling the log function.
P-1.31) Hint While not always optimal, you can design your algorithm so
that it always returns the largest coin possible until the value of the change
is met.
P-1.32) Hint Do a case analysis to categorize each line of input.
6 Chapter 1. Python Primer
P-1.33) Hint Write your program to loop continually until a quit operation
is entered. In each iteration, collect a sequence of button pushes, and then
output the result from processing that sequence of pushes.
P-1.34) Hint Define a way of indexing all the sentences and the location
in each one and then work out a way of picking eight of these locations
for a typo.
P-1.35) Hint Use a two-dimensional list to keep track of the statistics and
a one-dimensional list for each experiment.
P-1.36) Hint You need some way of telling when you have seen the same
word you have before. Feel free to just search through your list of words
to do this here.