Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ksylvan
Last active May 4, 2020 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksylvan/41ff53be0156c9279229fda86dafeab2 to your computer and use it in GitHub Desktop.
Save ksylvan/41ff53be0156c9279229fda86dafeab2 to your computer and use it in GitHub Desktop.
Euler 17 in Python: Number to words
# 1 <= T <= 10
# 0 <= N <= 1e12
# 1e3 = Thousand
# 1e6 = Million
# 1e9 = Billion
# 1e12 = Trillion
# Project Euler 17
def number_hundres(n):
n %= 1000
up_to_20 = {
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"
}
the_tens = {
2: "Twenty", 3: "Thirty", 4: "Forty",
5: "Fifty", 6: "Sixty", 7: "Seventy",
8: "Eighty", 9: "Ninety"
}
hundreds, rest = divmod(n, 100)
s = []
if hundreds:
s.append(up_to_20[hundreds] + " Hundred")
if rest:
if rest < 20:
s.append(up_to_20[rest])
else:
tens, rest = divmod(rest, 10)
s.append(the_tens[tens])
if rest:
s.append(up_to_20[rest])
return s
def number_to_words(n):
if n == 0:
return "Zero"
s = []
postfixes = [
"", "Thousand", "Million", "Billion", "Trillion"
]
i = 0
while n:
h = number_hundres(n)
if h:
s.append((postfixes[i], h))
n //= 1000
i += 1
return " ".join(" ".join(o[1]) + " " + o[0] for o in reversed(s))
t = int(input())
for _ in range(t):
print(number_to_words(int(input())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment