我試圖通過使用實際的單詞和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)
嘗試當我在Python 2.7.11使用你的代碼,它說num2words不存在。也許它只適用於python 3?我不想用這種方式。 –
pip安裝num2words –