Jump to content

Converting integers to words using python 2.7

- - - - -

  • Please log in to reply
1 reply to this topic

#1
downeasta

downeasta

    Newbie

  • Members
  • Pip
  • 1 posts
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?

#2
Sysop_fb

Sysop_fb

    Programmer

  • Members
  • PipPipPipPip
  • 160 posts
  • Location:Missouri
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

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.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users