Skip to content Skip to sidebar Skip to footer

Think Python (how To Think Like A Computer Scientist) - Excercise 8.4

I'm having some trouble solving the problem below (My thinking on how I might solve it is directly beneath the problem) 'In Robert McCloskey’s book Make Way for Ducklings, the

Solution 1:

>>> for letter in prefixes:
        if letter in ('O', 'Q'):  # if the letter is O or Qprint letter + 'u' + suffix
        else:
            print letter + suffix


Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack

Solution 2:

My solution would be:

prefixes = list('JKLMNP')
prefixes.extend(['Ou', 'Qu'])
suffix = 'ack'for pref in prefixes:
    print pref + suffix

It is compact and contains very few modifications of the original.

Solution 3:

I just did this exercise and came here to see how others did it. In my 2nd edition this was part of a chapter on indexing and the string module, so I used them heavily in my nutso solution. Basically I added the "u"s to the prefix string and wrote an if statement to check for lowercase in the string.

import string
def ducks():
    prefixes = "JKLMNOuPQu"
    suffix = "ack"index = 0whileindex < len(prefixes)-1:
        if prefixes[index+1] in string.lowercase:
        prefix = prefixes[index:index+2]
        print prefix + suffix
        index += 1
    elif prefixes[index] in string.lowercase:
        index += 1else:
        prefix = prefixes[index]
        print prefix + suffix
        index +=1

Solution 4:

I think you're overthinking this. You just need to check within the loop if the current letter is O or Q, and if so add a U.

Solution 5:

I like data-driven code:

endings = ['ack', 'uack']
specials = ['O','Q']
prefixes = 'JKLMNOPQ'
suffixes = dict(zip(prefixes, [endings[p in specials] for p in prefixes]))
for letter in prefixes:
    print letter + suffixes[letter]

Post a Comment for "Think Python (how To Think Like A Computer Scientist) - Excercise 8.4"