[英]Project Euler Problem 17, Python, I Am getting wrong Answer, No Idea why
”问题17:如果用单词写出数字1到5:一、二、三、四、五,那么总共用了3 + 3 + 5 + 4 + 4 = 19个字母。
如果把1到1000(一千)的数字全部用文字写出来,要用多少个字母?
注意:不要计算空格或连字符。 例如,342(三百四十二)包含 23 个字母,115(一百一十五)包含 20 个字母。 在写数字时使用“and”符合英国的习惯。”
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 。
我不知道我做错了什么,我知道回答时会很愚蠢。
如果您打印结果,则代码中存在问题:
800 : EightAndHundred
python 内的模块inflect允许将数字转换为单词。 以下代码对我来说很好用。
`import inflect
p = inflect.engine()
def count_digits(a, b):
total_count = 0
for i in range(a, b + 1):
total_count += digit_to_word(i)
return total_count
def digit_to_word(j):
word = list(p.number_to_words(j))
count = 0
for k in word:
if k not in [',', '-', ' ']:
count += 1
return count
sum1 = count_digits(1, 1000)
print(sum1)`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.