我写了下面的代码,假设将所有数字从1到9999转换成单词,但我正在超出范围的数字,如111等。请帮助。谢谢。在
global n2W
n2W = {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:'one hundred', 200:'two hundred',\
300:'three hundred', 400:'four hundred',500:'five hundred', 600:'six hundred',\
700:'seven hundred',800:'eight hundred', 900:'nine hundred',\
1000:'one thousand', 2000:'two thousand', 3000:'three thousand',\
5000:'five thousand', 6000:'six thousand', 7000:'seven thousand',\
8000:'eight thousand', 9000:'nine thousand',10000:'ten thousand'}
def num2Word(n):
try:
print (n2W[n])
except KeyError:
try:
print (n2W[n-n%10] , n2W[n%10].lower())
except KeyError:
print ("Number out of range")
n = eval(input("Please enter a number between 1 and 9999 inclusive: "))
num2Word(n)
看看这个解决方案,在这个方案中,我们从左到右迭代数字位数,在每次迭代中将
value
映射到文本,然后放弃最有效的数字。在例如,对于n=1234,我们将有四次迭代,其中
value
等于:value
=1000value
=200value
=30value
=4你只尝试一次,这意味着这将工作最多2位数。试着递归地做。如果你想要,我可以给你一个有效的答案。 不要执行n2W[n%10].lower(),而是使用对num2Word的递归调用。在
只需手动插入一个数字就可以看出为什么会出错
例如,尝试n=111
(n2W[n-n%10] , n2W[n%10].lower())
111%10=1
,因此您有:n2W[110]
和{n2W[110]
是你的关键错误,它只需要递归到你的函数中。在相关问题 更多 >
编程相关推荐