Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Think Python (How to think like a computer scientist) - Excercise 8.4

Tags:

python

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 names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack."

This loop outputs these names in order:

prefixes = 'JKLMNOPQ' 
suffix = 'ack'
for letter in prefixes:
    print letter + suffix

The output is:

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Of course, that’s not quite right because “Ouack” and “Quack” are misspelled.

Exercise 8.2 Modify the program to fix this error."

So prefix + suffix yields 4 characters in its current form. Ouack and Quack are 5 characters. In the prior section, we used 'while' to transverse a string to create a condition where if the index is equal to the length of the string, the condition is false, and the body of the loop is not executed. I'm thinking I need to modify the for loop so that if the output character count is less than the original string value inputted, it adds the letter 'U'. How do I go about relating the length of the string value inputted for each name and the 'prefixes'?

I'm not sure how I'd go about doing this, or if I should persue a different strategy.

I apologize in advance I've butchered any of the terminology, I'm two days into this book, and I have no prior computer science background.

like image 493
Alex Karpowitsch Avatar asked Dec 02 '25 08:12

Alex Karpowitsch


1 Answers

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


Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack
like image 53
user225312 Avatar answered Dec 03 '25 22:12

user225312



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!