Thursday, December 9, 2010

Wordify

This code can count to a million in words. It could probably be refactored so it was shorter and could count to any number. If you were patient enough.

The "-b" flag puts "and" in the places a Brit would put it. It's optional but preferred.
I have random stopping points to increase the modest entertainment value of it running.

Can you recursively get wordify up to the quintillions? How should the "-b" flag be handled?

Can you do this in French?


from string import ascii_lowercase as alphabet
from sys import argv

units = [""] + "one two three four five six seven eight nine".split()
teens = "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
tenties = 2 * [""] + "twenty thirty forty fifty sixty seventy eighty ninety".split()


def name(number,terminate = True,continued = False,brit=False):
assert type(number) == int
assert number > 0 and number < 1001
if number == 1000: return "one thousand"
hundreds,residual = divmod(number,100)
tens,ones = divmod(residual,10)
result = ""
if hundreds:
result += units[hundreds] + " hundred"
if residual and hundreds:
result += " "
if brit and residual and (hundreds or continued):
result += "and "
if (tens == 1):
result += teens[ones]
if terminate:
result += "."
else:
if tens:
result += tenties[tens]
if ones: result += "-"
if ones:
result += units[ones]
if terminate:
result += "."
return result

def wordify(number,brit=False):
assert type(number) == int
assert number > 0 and number < 1000000
thousands,residual = divmod(number,1000)
result = ""
if thousands:
result = name(thousands,False,brit=brit) + " thousand"
if residual:
result += " "
result += name(residual,continued = True,brit=brit)
else:
result += "."
else:
result = name(number)
return result

if __name__ == "__main__":

from time import sleep
from random import randint

brit = "-b" in argv

sleeper = 30
for i in range(1,1000000):
if i == sleeper:
sleep(3)
sleeper += randint(3000,90000)
print wordify(i,brit=brit)



output:


one.
two.
three.
four.
five.
six.
seven.
eight.
nine.
ten.
eleven.
twelve.
...
nine hundred and ninety-nine thousand nine hundred and ninety-six.
nine hundred and ninety-nine thousand nine hundred and ninety-seven.
nine hundred and ninety-nine thousand nine hundred and ninety-eight.
nine hundred and ninety-nine thousand nine hundred and ninety-nine.


That's as far as it goes so far. Go fix it.

No comments: