In one of my CS classes, the assignment first asks us to write a program that will efficiently print out all the lyrics to the song "99 bottles of beer".
Here's my code for the first part of the assignment.
for beer in range(99, 0, -1):
if beer > 1:
print beer, "bottles of beer on the wall,", beer, "bottles of beer."
if beer > 2:
suffix = str(beer - 1) + " bottles of beer on the wall."
else:
suffix = "1 bottle of beer on the wall."
elif beer == 1:
print "1 bottle of beer on the wall, 1 bottle of beer."
suffix = "no more beer on the wall! Go to the store and buy some more, 99 bottles of beer on the wall."
print "Take one down and pass it around,", suffix
print "--"
The second part of the assignment asks us to perform the same task, except spell each number out. (ex. 99="Ninety-nine", etc)
Can anyone shed some light on how this can be done?
1 reply to this topic
#1
Posted 23 January 2012 - 04:16 PM
|
|
|
#2
Posted 23 January 2012 - 05:32 PM
I'd personally just use a dictionary and write a function to put everything together into a string and return it to me here's an example for 1-9
The teens would be the only special case really since 28 is twenty eight so all you'd need is a twenty in the dict.
numwords = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', \
5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
#num passed in int format
def numtowords(num):
length = len(str(num))
if length == 1:
return numwords[num]
The teens would be the only special case really since 28 is twenty eight so all you'd need is a twenty in the dict.
"The best optimizer is between your ears" - Michael Abrash
Saying you can optimize a program is like saying you understand how a program works on every level of every facet on a specific machines configuration.
Saying you can optimize a program is like saying you understand how a program works on every level of every facet on a specific machines configuration.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top










