-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnumber_names.py
128 lines (108 loc) · 2.8 KB
/
number_names.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""
Problem
-------
**Number Names**
Show how to spell out a number in English.
You can use a preexisting implementation
or roll your own, but you should support
inputs up to at least one million (or the maximum
value of your language's default bounded integer
type, if that's less). *Optional: Support for
inputs other than positive integers
(like zero, negative integers, and
floating-point numbers).*
Solution
--------
The solution is provided in a recursive way.
Using a dictionary mapping the number with the
related name
Author
------
dbonadiman
"""
import sys
def digit_to_name(n):
"""
digit_to_name
This recursive function takes in input a number
and outputs the name of the number in english
Parameters:
n ==> The number in input(it must be and integer)
Test:
>>> digit_to_name(3)
'three'
>>> digit_to_name(33)
'thirty-three'
"""
onetotwenty = {
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: "fiveteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen"
}
dec = {
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety"
}
uptotrillion = {
1000000000000: "trillion",
1000000000: "billion",
1000000: "million",
1000: "thousand",
100: "hundred"
}
for dig in uptotrillion:
if int(n/dig) != 0:
if n % dig == 0:
return "".join([digit_to_name(int(n / dig)),
" ", uptotrillion[dig]])
else:
return "".join([digit_to_name(int(n / dig)),
" ", uptotrillion[dig],
" ", digit_to_name(n % dig)])
if n < 100 and n >= 20:
for dig in dec:
if n-dig < 10 and n-dig > 0:
return "".join([dec[dig], "-", digit_to_name(n-dig)])
elif not n-dig:
return dec[dig]
return onetotwenty[n]
def main():
try:
print("\nThis program takes in input an integer and outputs\n"
"the number's name in english\n"
"Please enter the number:\n")
n = int(raw_input("-->"))
if not n:
raise ValueError("Only numbers greather than 0 allowed")
print(digit_to_name(n))
return 0
except Exception, e:
print(e)
return 1
if __name__ == "__main__":
import doctest
doctest.testmod()
status = main()
sys.exit(status)