Problem 17

Problem 17

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
如果1到5写成英语,然后再把英语单词的字母数量加起来,我们会得到19。
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
如果所有的从1到1000(包括1000)的数字都写成英语单词,那需要多少个字母呢?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen)
contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
注意:不要计算空白符以及连字符,需要计入‘and’单词。

def number_to_word(num: int) -> int:
    determine_thousand = lambda num: int(str(num)[-4]) if len(str(num)) >= 4 else 0
    thousand = determine_thousand(num)
    determine_hundred = lambda num: int(str(num)[-3]) if len(str(num)) >= 3 else 0
    hundred = determine_hundred(num)
    determine_ten = lambda num: int(str(num)[-2]) if len(str(num)) >= 2 else 0
    ten = determine_ten(num)
    one = int(str(num)[-1])

    word = 0
    if ten == 1:
        word += ten_to_twenty(int(str(num)[-2:]))
    else:
        word += one_digit(one)
        word += ten_digit(ten)
    word += hundred_digit(hundred)
    if hundred:
        if ten or one:
            word += 3  # and
    word += thousand_digit(thousand)
    return word


def one_digit(num: int) -> int:
    if num == 0:
        return 0
    word = 0
    if num in [1, 2, 6]:  # one, two, six, ten
        word = 3
    elif num in [3, 7, 8]:  # three, seven, eight
        word = 5
    else:  # 4, 5, 9  four, five, nine
        word = 4
    return word


def ten_digit(num: int) -> int:
    if num == 0:
        return 0
    word = 0
    if num in [2, 3, 8, 9]:  # twenty, thirty, eighty, ninety
        word = 6
    elif num in [4, 5, 6]:  # forty, fifty, sixty
        word = 5
    elif num == 7:  # seventy
        word = 7
    return word


def hundred_digit(num: int) -> int:
    if num == 0:
        return 0
    word = 0
    word = one_digit(num)
    word += 7  # hundred
    return word


def thousand_digit(num: int) -> int:
    if num == 0:
        return 0
    word = 0
    word = one_digit(num)
    word += 8  # thousand
    return word


def ten_to_twenty(num: int) -> int:
    if num == 0:
        return 0
    word = 0
    if num == 10:  # ten
        word = 3
    elif num in [11, 12]:  # eleven, twelve
        word = 6
    elif num in [13, 14, 18, 19]:  # thirteen, fourteen, eighteen, nineteen
        word = 8
    elif num in [15, 16]:  # fifteen, sixteen
        word = 7
    elif num == 17:  # seventeen
        word = 9
    return word


if __name__ == '__main__':
    tot = 0
    for i in range(1001):
        word = number_to_word(i)
        print(i, word)
        tot += word
    print(tot)

猜你喜欢

转载自www.cnblogs.com/noonjuan/p/10962495.html
17