Python练习题 045:Project Euler 017:数字英文表达的字符数累加

时间:2023-02-22 22:34:52

本题来自 Project Euler 第17题:https://projecteuler.net/problem=17

'''
Project Euler 17: Number letter counts
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.
If all the numbers from 1 to 1000 (one thousand) inclusive
were written out in words, how many letters would be used?
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.

Answer: 21124
'''

n1 = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
n2 = ['', 'eleven', 'twelve', 'thirteen','fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
n3 = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

sum = ''  #所有数字的英文表达累加

for i in range(1, 1001):
    baiwei = i//100  #百位数
    shiwei = (i - baiwei*100)//10  #十位数
    gewei = i%10  #个位数
    eng = ''  #当前数字的英文写法

    if i == 1000:
        eng += 'onethousand'
    elif i%100 == 0:  #若为整百的
        eng = n1[baiwei] + 'hundred'
    elif i > 100:
        eng = eng + n1[baiwei] + 'hundredand'
        if shiwei == 1 and gewei != 0:
            eng += n2[gewei]
        else:
            eng = eng + n3[shiwei] + n1[gewei]
    elif i > 19:
        eng = eng + n3[shiwei] + n1[gewei]
    elif i > 10:
        eng += n2[gewei]
    elif i == 10:
        eng += 'ten'
    else:
        eng += n1[gewei]
    sum += eng  #累加各个数字的英文表达

print(len(sum))

老实说,看到这题的时候,我心里其实是不愿意做的:对于我这样的算法渣,肯定得写出N个 if 和 elif。但没办法,只好硬着头皮写,错了好几回之后,总算是把所有情况都考虑到了。擦汗……

大致思路是:把数字挨个儿转换成英文表达方式,累加起来,然后用 len() 计算总字符的长度即可。