"Euler计划问题17,Python,我得到错误的答案,不知道为什么"

2024-10-04 09:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果问题是1到5,那么1到5的问题是2到5 总共有3+3+5+4+4=19个字母。在

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

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

initDict1 = {1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine",
             11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen",
             18: "Eighteen", 19: "Nineteen",
             10: "Ten", 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty",
             90: "Ninety", 100: "Hundred", 1000: "Thousand"}
for num in range(1, 1001):
        if num < 101:
            if num not in initDict1:
                newNum = num // 10 * 10
                initDict1[num] = initDict1[newNum] + initDict1[num % 10]
                # print(num, " : ", initDict1[newNum] + initDict1[num % 10])
        elif num < 1000:
            newNum = num // 100
            newNum1 = (newNum * 100) // newNum
            if num % 100 != 0:
                initDict1[num] = initDict1[newNum] + initDict1[newNum1] + 'And' + initDict1[num % 100]
                # print(num, " : ", initDict1[newNum] + initDict1[newNum1] +'And'+ initDict1[num % 100])
            else:
                initDict1[num] = initDict1[newNum] + 'And' + initDict1[newNum1]
                # print(num, " : ", initDict1[newNum] + 'And' +initDict1[newNum1])

wordCount = 0
for num in initDict1.values():
    wordCount += len(num)
print(wordCount)

我得到的答案是21142,而要求的答案是21124。在

我不知道我做错了什么,我知道当我回答的时候会是愚蠢的。在


Tags: and答案inforif字母数字wordcount