This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
STRINGS = dict( | |
negative = ["negative"], | |
base = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", | |
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", | |
"sixteen", "seventeen", "eighteen", "nineteen"], | |
tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"], | |
powers = ["hundred", "thousand", "million", "billion", "trillion", "quadrillion", | |
"quintillion", "sextillion", "septillion", "octillion", "nonillion", | |
"decillion"], | |
) | |
ALL_STRINGS = reduce(lambda x, y: x + y, | |
[STRINGS[i] for i in ("negative", "base", "tens", "powers")]) | |
def number(n): | |
if n < 0: | |
return STRINGS["negative"][0] + " " + number(-n) | |
if n < 20: | |
return STRINGS["base"][n] | |
if n < 100: | |
if n % 10 == 0: | |
return STRINGS["tens"][(n / 10) - 2] | |
return number(n / 10 * 10) + "-" + number(n % 10) | |
if n < 1000: | |
return number(n / 100) + " " + STRINGS["powers"][0] + " " + number(n % 100) | |
for i in range(1, len(STRINGS["powers"])): | |
power = i * 3 | |
if n < 10 ** (power + 3): | |
if n % (10 ** power) == 0: | |
return number(n / 10 ** power) + " " + STRINGS["powers"][i] | |
return number(n / (10 ** power) * (10 ** power)) + " " + number(n % (10 ** power)) | |
raise ValueError("%d is too big for this function to undestand" % n) | |
def main(argv): | |
if len(argv) < 2: | |
print >> sys.stderr, "Usage: %s {<number>|<start>..<end>|test} ..." | |
return 2 | |
for arg in argv[1:]: | |
if arg.lower() != "test": | |
n, end, step = (arg.split("..") + [1])[:3] if ".." in arg else [arg, arg, 1] | |
n, end, step = [int(n) for n in (n, end, step)] | |
while n <= end: | |
print number(int(n)) | |
n += step | |
else: | |
import random | |
for n in (-1, 0, 16, 320, 4096, 16384, 654321, 1000000, 20000576, 123456789): | |
print "%d: %s" % (n, number(n)) | |
n = random.randint(10**8, 10**9-1) | |
while True: | |
n = n * 10 + random.randint(0,9) | |
try: | |
print "%d: %s" % (n, number(n)) | |
except ValueError: | |
break | |
if __name__ == "__main__": | |
try: | |
sys.exit(main(sys.argv)) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment