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)います。50 はあなたのifステートメントでカバーされていないため、再度取得し、else再度呼び出しますconvert(50)

于 2013-03-28T21:40:30.197 に答える
2

ここでの問題はround(46, -1)、値が生成されることです50。がconvert値で呼び出されると50、まったく同じ行に移動します

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

round(50, -1)呼び出しが生成され、この50時点でconvert関数が無限に実行されます

于 2013-03-28T21:41:26.247 に答える