Last active
August 29, 2015 14:14
-
-
Save toshsan/58885617bba570c62dcc to your computer and use it in GitHub Desktop.
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/python | |
zeroTo19 = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", | |
"ten", "eleven", "twelve", "thirteen", "fourteeen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] | |
tens = [ "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" ] | |
denoms = [ (1000000000000, "trillion"), (1000000000, "billion"), (1000000, "million"), (1000, "thousand"), (100, "hundred") ] | |
def num2words(n): | |
if n<20: | |
return zeroTo19[n] | |
words = None | |
if n<100: | |
t, n1 = divmod(n, 10) | |
words = tens[t] | |
if n1>0: words += " " + zeroTo19[n1] | |
return words | |
for (d, w) in denoms: | |
if n >= d: | |
den, rem = divmod(n, d) | |
words = num2words(den) + " " + w | |
if rem >0: words += " " + num2words(rem) | |
return words | |
if __name__ == '__main__': | |
import random | |
import timeit | |
import platform | |
from multiprocessing import cpu_count | |
rand = random.Random() | |
rand.seed() | |
test_data=[ | |
(1000000000001, "one trillion one"), | |
(1000000000000, "one trillion"), | |
(999999999999, "nine hundred ninety nine billion nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine"), | |
(1000000001, "one billion one"), | |
(1000000000, "one billion"), | |
(999999999, "nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine"), | |
(1000001, "one million one"), | |
(1000000, "one million"), | |
(999999, "nine hundred ninety nine thousand nine hundred ninety nine"), | |
(1001, "one thousand one"), | |
(1000, "one thousand"), | |
(999, "nine hundred ninety nine"), | |
(101, "one hundred one"), | |
(100, "one hundred"), | |
(99, "ninety nine"), | |
(405478, "four hundred five thousand four hundred seventy eight") | |
] | |
for (n, words) in test_data: | |
assert(num2words(n) == words) | |
print n, num2words(n) | |
r = rand.randint(0, 1000000000000) | |
print r, ":", num2words(r) | |
def benchmark(): | |
r = rand.randint(0, 1000000000000) | |
num2words(r) | |
print "=========================================================" | |
print "Benchmarking on", cpu_count(), "CPU(s)", platform.uname() | |
t = timeit.Timer(benchmark) | |
print(t.timeit()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment