简体   繁体   中英

Project Euler Prob 7 Python

I've tried to tackle this problem by using the actual words and the len() function. I keep getting 21224 but the answer is 21124. Can someone please explain why? Here's the problem.

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.

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)

Check your spelling of forty. The proper way to spell it is 'forty' not 'fourty' .

you can try with this

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM