繁体   English   中英

为什么我的程序没有打印出 Project Euler 17 的正确答案?

[英]Why is my program not printing the right answer for Project Euler 17?

欧拉计划第17 题

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

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

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

每当我用一个随机生成的数字测试我的代码时,如果该数字用文字写成,它就会输出正确的字符数。 但是,当尝试使用提供的测试用例运行时,我的答案是错误的。 答案:18451

Words = {0: "", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen",17:"seventeen", 18:"eighteen", 19:"nineteen", 20:"twenty", 30:"thirty", 40:"forty", 50:"fifty", 60:"sixty", 70:"seventy", 80:"eighty", 90:"ninety", 100:"onehundred", 200:"twohundred", 300:"threehundred", 400:"fourhundred", 500:"fivehundred", 600:"sixhundred", 700:"sevenhundred", 800:"eighthundred", 900:"ninehundred", 1000:"onethousand"}

count = 0
for i in range(1, 1001):
    c = 1
    arr = []
    if(i<=20 or (len(str(i))==2 and i%10==0)):
        count += len(Words.get(i))

    elif(i%100==0):
        count += len(Words.get(i))

    else:
        while(i!=0):
            z = i%10
            arr.append(z*c)
            i = i//10
            c*=10

        if(len(arr)==3 and arr[1]==10):
            arr[1]=arr[1]+arr[0]
            arr[0]=0
        for f in arr:
            count+=len(Words.get(f))
    
print(count)

我已经调试了你的代码。 您在问题中提到 115(一百一十五)有 20 个字母,但您的程序计数为 17,因为您没有在代码中考虑“和”。 如果你包括每个“和”,你会得到 891 * 3 + 18451 = 21124 我相信这是正确的答案。 希望我不会误会数学。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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