我正在制作一个程序来获取数字中的字母数量:
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)