Python 中的 Collat​​z 猜想

Collatz Conjecture in Python

我对 Python 比较陌生,因此我决定尝试编写一个相对简单的 collat​​z 猜想,用户在其中输入一个数字(整数)。该代码只是一个调用自身的简单函数。 i 是一个列表,它应该附加函数计算的每个数字。我是执行 Python 脚本的新手,我尝试使用 IDLE shell 来 运行 代码。它问我想要什么号码,但是当我输入一个号码时什么也没有打印出来?我确信我只需要编辑这段代码的一小部分(或者可能都是错误的)但是有人知道为什么我的脚本 returns 什么都没有吗?对此感到抱歉,谢谢。 这是代码:

l = input("Enter a number: ")
l = int(l)
i = []
def collatz(n):
    if n==1:
        return i
    if n%2 == 0:
        n = n/2
        i.append(n)
        return collatz(n)
    else:
        n = ((n*3) + 1) / 2
        i.append(n)
        return collatz(n)
    print(i)
collatz(l)

在你的 print 之前有三个 return,其中一个在 else 语句中,这意味着至少其中一个将被执行,所以你的 print 甚至不会被执行,你应该把它移到函数定义之后才能看到一些东西:

def collatz(n):
    print(i) # <= print here
    if n==1:
        ....

查看有关 return statement 的更多信息。一个片段:

return leaves the current function call with the expression list (or None) as return value.

正如其他人所提到的,函数中的所有执行路径都以 return 语句结尾,因此无法访问 print 调用。因此,如果您希望打印 ni 的每个值,您需要将调用移动到 可达的地方。 ;)

另外,该代码中有一点冗余。你不需要

i.append(n)
return collatz(n)

ifelse 分支中,您可以将它们移到 if...else 块之外。

这是您的代码的修改版本。我还将 / 运算符更改为 //,这样除法的结果就是整数。

i = []

def collatz(n):
    print(n)
    if n==1:
        return i
    if n%2 == 0:
        n = n // 2
    else:
        n = ((n*3) + 1) // 2
    i.append(n)
    return collatz(n)

# Test

print(collatz(12))

输出

12
6
3
5
8
4
2
1
[6, 3, 5, 8, 4, 2, 1]