say.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
POWERS = (
    (1000000000, 'billion'),
    (1000000, 'million'),
    (1000, 'thousand'),
    (100, 'hundred'),
)

NUMBERS = dict(enumerate((
    "zero", "one", "two", "three", "four", "five", "six", "seven",
    "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
    "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
)))


TENS = dict(enumerate((
    "twenty", "thirty", "forty", "fifty",
    "sixty", "seventy", "eighty", "ninety",
), 2))


def say(n):
    if n < 0:
        raise AttributeError("Negative number not allowed")

    if n >= 1e12:
        raise AttributeError("Number is too large")

    if n < 20:
        return NUMBERS[n]

    if n < 100:
        tens = TENS[n / 10]
        if n % 10 == 0:
            return tens
        else:
            return '{}-{}'.format(tens, say(n % 10))

    for power, name in POWERS:
        if n >= power:
            say_power = '{} {}'.format(say(n / power), name)
            rest = n % power
            if rest == 0:
                return say_power
            elif rest < 100:
                return '{} and {}'.format(say_power, say(rest))
            else:
                return '{} {}'.format(say_power, say(rest))

@Eugene-1984 thinks this looks great

Comments


You're not logged in right now. Please login via GitHub to comment