0

尝试构建一个递归定义,该定义将计算数字“7”在给定数字中出现的次数。我不明白为什么我的回报一直没有给我。

def count7(N):
    '''
    N: a non-negative integer
    '''
    x = 0
    def helpcount7(N,x):
        Ld = N % 10
        NewN = N // 10
        if Ld == 7:
            x +=1
        if NewN != 0:
            helpcount7(NewN,x)
        else:
            print(x)
    return helpcount7(N,x)


print(count7(717))

例如,如果我输入 717,我的答案将是:

2 无

4

1 回答 1

0

原因是你没有从你的helpcount7()函数中返回任何东西。你应该从中返回一些东西,例如:

def count7(N):
    '''
    N: a non-negative integer
    '''
    x = 0
    def helpcount7(N,x):
        Ld = N % 10
        NewN = N // 10
        if Ld == 7:
            x +=1
        if NewN != 0:
            return helpcount7(NewN,x)
        else:
            return x
    return helpcount7(N,x)


print(count7(717))
于 2020-07-03T23:41:35.667 回答