2

我正在制作一个程序来获取数字中的字母数量:

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)
4

2 回答 2

4

因为当你这样做时

convert(int(round(number, -1)))

你在打电话convert(50)。由于您的if语句未涵盖 50,因此它会else再次调用,并再次调用convert(50),依此类推。

于 2013-03-28T21:40:30.197 回答
2

这里的问题是round(46, -1)会产生 value 50。当convert使用该值调用时,50它将转到完全相同的行

lettercount += convert(int(round(number, -1)))

round(50, -1)调用将产生,50此时convert函数将无限执行

于 2013-03-28T21:41:26.247 回答