Skip to content

Instantly share code, notes, and snippets.

@dpyro
Created March 1, 2017 01:47
Show Gist options
  • Save dpyro/6ec5f89db49fa952ace402b9af92cc42 to your computer and use it in GitHub Desktop.
Save dpyro/6ec5f89db49fa952ace402b9af92cc42 to your computer and use it in GitHub Desktop.
produces an English phrase given an integer
#!/usr/local/bin/python3
# pylint: disable=C0103, C0111
def english_phrase(num):
"""Returns an English phrase string for an integer n."""
n = int(num)
negative_name = "negative"
names = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety",
}
big_names = {
100: "hundred",
1000: "thousand",
1000000: "million",
1000000000: "billion",
1000000000000: "trillion",
1000000000000000: "quadrillion",
# I could go on. But I won't. But I could.
}
assert abs(n) < 1000*max(big_names), "{} is too large for {}".format(n, __name__)
output = []
negative = False
if n < 0:
negative = True
n = abs(n)
if n == 0:
output.append(names[0])
else:
def english_phrase_triplet(num):
"""Returns an English phrase for an integer n where 0 < n < 1000."""
n = int(num)
assert 0 < n < 1000
output = []
hundreds = n // 100
if hundreds > 0:
output.append(names[hundreds])
output.append(big_names[100])
n -= hundreds*100
if n != 0:
if n in names:
output.append(names[n])
else:
ones = n%10
tens = (n//10)*10
output.append(names[tens])
output.append(names[ones])
result = " ".join(output)
return result
while n > 0:
if n in names:
output.append(names[n])
break
elif n >= 1000:
bigs = reversed(sorted(big_names.keys()))
multiplier = 0
for big in bigs:
if n >= big:
multiplier = big
break
triplet = n // multiplier
triplet_output = " ".join(
[english_phrase_triplet(triplet),
big_names[multiplier]]
)
output.append(triplet_output)
n -= triplet*multiplier
else:
output.append(english_phrase_triplet(n))
break
result = ", ".join(output)
if negative:
result = "{} {}".format(negative_name, result)
return result
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print("Usage: {} n".format(__file__), file=sys.stderr)
sys.exit(1)
result = english_phrase(sys.argv[1])
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment