I was asked to take this code:
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
print letter + suffix
which produced the following output:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
and rewrite it so that Oack and Qack would actually be Ouack and Quack. Here is what I did:
prefix = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefix:
if letter == 'Q' or letter == 'O':
print letter + 'u' + suffix
else:
print letter + suffix
Here was the result:
Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack
Yay! I’m going to revisit it though and see if there is a better way of coding it. For now, I’m just happy it worked.
February 1st, 2008 at 8:46 am
the solution is good, for a quick and dirty one. But if someone also asked you to change Jack to Jiack, Kack to Keack, and so on and so on, you would have to add more exceptional cases to your logic, wich would quickly make it rather complicated. consider adding the exceptional cases to the data instead, allowing you to keep the logic as it is:
prefixes = ['J', 'K', 'L', 'N', 'M', 'N', 'Ou', 'P', 'Qu']
the rest of the code would be like the original example. This works, and allows you to go in and change other letters without making the code longer or more complicated
February 1st, 2008 at 8:48 am
by the way, I know I’m commenting pretty old posts right now, but just in case another python newcomer comes by, I did it anyway. If he learns something from this, it will have been worth it