Python函数返回无.为什么?

Irm*_*nis 1 python python-2.7

count = []

def problem14(n):
    count.append(n)
    if n == 1:
        return count
    if n % 2 == 0:
        n = n/2
        problem14(n)
    else:
        n = 3*n + 1
        problem14(n)


print problem14(13)
Run Code Online (Sandbox Code Playgroud)

所以这是我写的代码.我不知道为什么它会返回None,而在我看来它应该返回列表'count'.有帮助吗?

ars*_*jii 9

使用递归时仍需要return语句,否则返回值将丢失:

def problem14(n):
    count.append(n)
    if n == 1:
        return count
    if n % 2 == 0:
        n = n/2
        return problem14(n)  # <--
    else:
        n = 3*n + 1
        return problem14(n)  # <--
Run Code Online (Sandbox Code Playgroud)

顺便说一句,对于Project Euler#14来说这可能是错误的方法:-)考虑使用动态编程方法(这就是我所说的所有这一切,以免破坏乐趣).