grimoire/python/number-words.py

65 lines
1.3 KiB
Python

import collections
import sys
DIGITS = {
"1": ["one", "ten", "eleven"],
"2": ["two", "twenty", "twelve"],
"3": ["three", "thirty", "thirteen"],
"4": ["four", "forty", "fourteen"],
"5": ["five", "fifty", "fifteen"],
"6": ["six", "sixty", "sixteen"],
"7": ["seven", "seventy", "seventeen"],
"8": ["eight", "eighty", "eighteen"],
"9": ["nine", "ninety", "nineteen"]
}
PLACES = [
"", "thousand", "million", "billion", "trillion"
]
number = "42"
if len(sys.argv) > 1:
number = sys.argv[1]
idx = len(number)
groups = []
while idx > 0:
start = idx - 3
if start < 0:
start = 0
groups.append(number[start:idx])
idx = start
word = collections.deque([])
idx = 0
for group in groups:
special = False
combined = []
if len(group) == 3 and group[0] != "0":
combined.append(DIGITS[group[0]][0] + " hundred")
if len(group) > 1:
if group[-2] == "1" and group[-1] != "0":
combined.append(DIGITS[group[-1]][2])
special = True
elif group[-2] in DIGITS:
combined.append(DIGITS[group[-2]][1])
if not special and group[-1] in DIGITS:
combined.append(DIGITS[group[-1]][0])
if group != "000":
combined.append(PLACES[idx])
if len(combined) > 0:
word.appendleft(" ".join(combined))
idx += 1
print(" ".join(word).rstrip())