我正在为Timothy A.Budd的(探索Python)书中学习python
我的问题是本书第三章中关于定义函数的第一个问题:
将整数转换为等效字符串的程序也无法处理 负数或零正确。这通过创建一个最容易处理 第二个函数将这些识别为特殊情况,然后调用 一般情况下的递归函数。写下第二个功能。为什么不能 递归函数在给定值0时返回“零”
将整数转换为等效字符串的程序在这里:
def numToString (num):
if num==0: return ''
elif num==1: return ' one '
elif num==2: return ' two '
elif num==3: return ' three '
elif num==4: return ' four '
elif num==5: return ' five '
elif num==6: return ' six '
elif num==7: return ' seven '
elif num==8: return ' eight '
elif num==9: return ' nine '
elif num==10: return ' ten '
elif num==11: return ' eleven '
elif num==12: return ' twelve '
elif num==13: return ' therteen '
elif num==14: return ' fourteen '
elif num==15: return ' fifteen '
elif num==16: return ' sixteen '
elif num==17: return ' seventeen '
elif num==18: return ' eighteen '
elif num==19: return ' ninteen '
elif num<=29: return ' twenty ' + numToString(num%10)
elif num<=39: return ' thirty ' + numToString(num%10)
elif num<=49: return ' fourty ' + numToString(num%10)
elif num<=59: return ' fifty ' + numToString(num%10)
elif num<=69: return ' sixty ' + numToString(num%10)
elif num<=79: return ' seventy ' + numToString(num%10)
elif num<=89: return ' eighty ' + numToString(num%10)
elif num<=99: return ' ninty ' + numToString(num%10)
elif num<=999: return numToString(num/100)+ ' hundred ' + numToString(num%100)
答案 0 :(得分:2)
如果函数为0返回'零',则numToString(20)将返回'二十零',依此类推。
答案 1 :(得分:0)
可能不在主题,但您可以使用dict(或本例中的列表)来减少代码:
def numToString (num):
words=[
'', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ',
' ten ', ' eleven ', ' twelve ', ' therteen ', ' fourteen ', ' fifteen ', ' sixteen ', ' seventeen ', ' eighteen ', ' ninteen ']
if num<20: return words[num]
elif num<=29: return ' twenty ' + numToString(num%10)
elif num<=39: return ' thirty ' + numToString(num%10)
elif num<=49: return ' fourty ' + numToString(num%10)
elif num<=59: return ' fifty ' + numToString(num%10)
elif num<=69: return ' sixty ' + numToString(num%10)
elif num<=79: return ' seventy ' + numToString(num%10)
elif num<=89: return ' eighty ' + numToString(num%10)
elif num<=99: return ' ninty ' + numToString(num%10)
elif num<=999: return numToString(num/100)+ ' hundred ' + numToString(num%100)