Project Euler Prob 7 Python

时间:2016-11-18 05:53:20

标签: python

我试图通过使用实际的单词和len()函数来解决这个问题。我一直得到21224,但答案是21124.有人可以解释一下原因吗?这就是问题所在。

如果数字1到5用文字写出:一,二,三,四,五,那么总共有3 + 3 + 5 + 4 + 4 = 19个字母。

如果所有1到1000(一千)的数字都用文字写出来,会用多少个字母?

注意:不要计算空格或连字符。例如,342(三百四十二)包含23个字母,115(一百一十五)包含20个字母。使用"和"写出数字符合英国人的用法。

one_nine='onetwothreefourfivesixseveneightnine'
ten_nineteen='teneleventwelvethirteenfourteenfifteensixteenseventeeneighteennineteen'
twenty_ninety_byten='twentythirtyfourtyfiftysixtyseventyeightyninety'
one_ninetynine_list=[one_nine*9,ten_nineteen,twenty_ninety_byten*10]
one_ninetynine=''.join(one_ninetynine_list)

onehundred_ninehundred_byonehundred_list=[one_nine,'hundred'*9]
onehundred_ninehundred_byonehundred=''.join(onehundred_ninehundred_byonehundred_list)
one_onethousand_list=[one_ninetynine*10,onehundred_ninehundred_byonehundred*100,'and'*891,'onethousand']
one_onethousand=''.join(one_onethousand_list)
print len(one_onethousand)

2 个答案:

答案 0 :(得分:1)

检查你的四十分拼写。拼写它的正确方法是'四十'而不是'四十'

答案 1 :(得分:0)

你可以试试这个

from num2words import num2words

list = []
for i in range(1, 1001):
    list.append(num2words(i, lang='en_GB'))

letters = 0
for element in list:
    for letter in element:
        if 97 <= ord(letter) <= 122:
            letters += 1

print(letters)