Display the names of numbers
This commit is contained in:
parent
c461e3a390
commit
851ac3fadb
1 changed files with 65 additions and 0 deletions
65
python/number-words.py
Normal file
65
python/number-words.py
Normal file
|
@ -0,0 +1,65 @@
|
|||
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())
|
Loading…
Add table
Reference in a new issue