python - 为什么我的程序没有打印出 Project Euler 17 的正确答案?
问题描述
欧拉计划第17 题:
如果数字 1 到 5 用单词写出:一、二、三、四、五,那么总共使用了 3 + 3 + 5 + 4 + 4 = 19 个字母。
如果用文字写出从 1 到 1000(一千)的所有数字,将使用多少个字母?
注意:不要计算空格或连字符。例如,342(342)包含 23 个字母,115(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 我相信这是正确的答案。希望我不会误会数学。
推荐阅读
- reactjs - 如何使用 React 自定义钩子重新获取深度嵌套的对象?
- linux - gcloud 在远程实例上执行命令未按预期工作
- python - 将 Python Telegram Bot 部署到 Heroku
- ios - 使用 Swift 在导航控制器中状态栏内容颜色不会变为白色
- typescript - 如何在 TypeScript 中使用动态键推断对象的类型?
- ios - 提供的实体中的属性具有无效值带有标识符“com.company.app”的应用 ID 不可用。请输入不同的字符串
- c# - Frozen Mock 返回 null 但在 Test 方法中工作正常
- macos - macOS .command 文件没有权限
- python - Conv2DTranspose 中的过滤器和内核大小应该是多少?
- unity3d - 滑块值不会因脚本/编辑器 Unity 而改变