2016-11-18 43 views
0

我試圖通過使用實際的單詞和len()函數來解決這個問題。我不斷得到21224,但答案是21124.有人可以解釋爲什麼嗎?這是問題。Project Euler Prob 7 Python

如果數字1至5用字寫出:1,2,3,4,5,則總共使用3 + 3 + 5 + 4 + 4 = 19個字母。

如果所有從1到1000(包括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) 

回答

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) 
+0

嘗試當我在Python 2.7.11使用你的代碼,它說num2words不存在。也許它只適用於python 3?我不想用這種方式。 –

+0

pip安裝num2words –