我做節目得到了一些信件量STR:的Python:最大遞歸深度而獲得一個物體的
def convert(number):
lettercount = 0
numstr = str(number)
# One's places
if len(numstr) is 1:
if number == 1 or number == 2 or number == 6:
lettercount += 3
elif number == 4 or number == 5 or number == 9:
lettercount += 4
else:
lettercount += 5
# Ten's places
elif len(numstr) is 2:
if number == 10:
lettercount += 3
elif number == 11 or number == 12:
lettercount += 6
elif number == 15 or number == 16:
lettercount += 7
elif number == 13 or number == 14 or number == 19:
lettercount += 8
elif number == 17 or number == 18:
lettercount += 9
elif number == 20 or number == 30 or number == 40 or\
number == 80 or number == 90:
lettercount += 6
else:
lettercount += convert(int((numstr)[-1]))
lettercount += convert(int(round(number, -1)))
return lettercount
print "88 has %i letters in its name." % convert(88)
print "23 has %i letters in its name." % convert(23)
print "46 has %i letters in its name." % convert(46)
它工作得很好,並返回88的正確響應和23,但它在46上給出了遞歸深度錯誤。我很困惑;爲什麼只發生在46歲?
固定碼:
def convert(number):
lettercount = 0
numstr = str(number)
# One's places
if len(numstr) == 1:
if number == 1 or number == 2 or number == 6:
lettercount += 3
elif number == 4 or number == 5 or number == 9:
lettercount += 4
else:
lettercount += 5
# Ten's places
elif len(numstr) == 2:
if number == 10:
lettercount += 3
elif number == 40 or number == 50:
lettercount += 5
elif number == 11 or number == 12 or number == 20 or number == 30 or\
number == 80 or number == 90:
lettercount += 6
elif number == 15 or number == 16:
lettercount += 7
elif number == 13 or number == 14 or number == 19:
lettercount += 8
elif number == 17 or number == 18:
lettercount += 9
else:
lettercount += convert(int((numstr)[-1]))
lettercount += convert((int(numstr) // 10) * 10)
return lettercount
print "88 has %i letters in its name." % convert(88)
print "23 has %i letters in its name." % convert(23)
print "46 has %i letters in its name." % convert(46)
因爲'輪(46,-1 )'是'50'。 – JBernardo
提示:不要使用len(numstr)是2',使用'len(numstr)== 2',因爲如果兩個對象在同一個內存點上,'is''只返回'True';如果值相同,'=='返回'True'。 –
@ F3AR3DLEGEND對於像2這樣的簡單整數,'is'測試將始終有效,因爲它是不可變的類型,所以它的所有實例都在相同的內存中。但我同意,只有在想要檢查兩個對象實際上是同一個對象時才應該使用'is'。 – lxop