以下是问题:
如果数字1到5用文字写出:一,二,三,四,五,那么总共有3 + 3 + 5 + 4 + 4 = 19个字母。
如果所有1到1000(一千)的数字都用文字写出来,会用多少个字母?
注意:不要计算空格或连字符。例如,342(三百四十二)包含23个字母,115(一百一十五)包含20个字母。在写出数字时使用“和”符合英国的用法。
我不明白为什么我的代码不会输出正确的答案。我已经多次检查过,我找不到任何我错过的东西。这是我的代码:
to_19 = [0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8]
tens = [0,3,6,6,5,5,5,7,6,6]
hundred = 7
thousand = 8
total = 0
for i in range(1,1000):
u = i%10
t = int(((i%100)-u) /10)
h = int(((i%1000)-(t*10)-u) /100)
print(h,t,u)
if i < 20: #the number is less than 20
total += to_19[i]
elif h != 0 and (t != 0 or u != 0): #the number is over 100 but not a multiple of 100
if t == 0 or t == 1: #the number is between x01 and x19
total += to_19[h] + hundred + 3 + to_19[(t * 10) + u]
else: #the number is between x20 and x99
total += to_19[h] + hundred + 3 + tens[t] + to_19[u]
elif t == 0 and u == 0: #the number is a multiple of 100
total += to_19[h] + hundred
else: #the number is between 20 and 99
total += tens[t] + to_19[u]
print(total+thousand)
#21121 is wrong
提前致谢!
答案 0 :(得分:2)
代码似乎足够合理。我没有仔细考虑您对u
,t
和h
的定义,但这似乎是正确的。我注意到你唯一遗失的是&#34;一个&#34;来自&#34;一千&#34;。
答案 1 :(得分:0)
我认为问题是您没有考虑“一百”和“五”之类的“和”。在该示例中,纯数字将是20个字母,但纯数字是23个。我希望对您有帮助
答案 2 :(得分:0)
from num2words import num2words # num2words - Convert numbers to words in multiple languages
def pro_17():
result = 0
for i in range(1,1001):
# Cancel spaces and add the length of the word
result+=(len(''.join(''.join(num2words(i).split('-')).split(' '))))
return result
print(pro_17()) # reslut ----> 21124