考拉兹猜想序列(Python 3)

4

我已经开始阅读Al Sweigart的"自动化无聊的事情"

在第3章末,作者建议用Python创建Collatz序列作为练习。 (练习建议使用print函数和return语句)

当我在我的代码中使用print()函数时,它很好地工作,并且我可以在屏幕上看到所有评估过的值:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))


def collatz(n):
    print(n)
    while n != 1:
        if n % 2 == 0:
            n = n // 2
            print(n)
        else:
            n = n * 3 + 1
            print(n)


collatz(user)

问题:
为什么当我想使用return语句时,while循环只运行一次?

例如,将整数3传递到我的函数中并使用return语句只会给我返回值3和10:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))


def collatz(n):
    print(n)
    while n != 1:
        if n % 2 == 0:
            n = n // 2
            return n
        else:
            n = n * 3 + 1
            return n


result = collatz(user)
print(result)

4
因为return会终止函数的执行。 - Robert Moskal
3个回答

3

return会退出函数,因此终止了你的while循环。

也许你想使用yield代替:

print("This is The Collatz Sequence")
user = int(input("Enter a number: "))

def collatz(n):
    print(n)
    while n != 1:
        if n % 2 == 0:
            n = n // 2
            yield(n)
        else:
            n = n * 3 + 1
            yield(n)

print(list(collatz(user)))

输出:

This is The Collatz Sequence
Enter a number: 3
3
[10, 5, 16, 8, 4, 2, 1]

Yield指的是一个函数和return类似,但是该函数并不会在执行完return或函数结尾之前终止执行。当执行yield语句时,生成器函数将被暂停,同时将yield表达式的值返回给调用者。一旦调用者完成(并且假设使用了已发送的值),则执行返回到在yield语句之后的生成器函数。


1
返回语句不仅会退出循环,还会退出函数! - Robert Moskal
真的。已编辑。谢谢! - dawg
我认为你可能需要添加一些解释,告诉OP yield是如何工作的 :) - Remi Guan
我现在明白了。谢谢你。使用return语句可以留在函数中吗? - R2DPoop
@R2DPoop:是的——使用 yield - dawg
@dawg 好的,现在我开始明白了。感谢你和其他所有人帮助回答我的问题。祝你周末愉快! - R2DPoop

2

在你的代码中,你没有将新值重新反馈到方程中。尝试将while循环与collatz模块分离。以下是一个示例:

def collatz(number):
    if number % 2 == 0:
        return number // 2
    elif number % 2 == 1:
        return 3 * number + 1

chosenInt = int(input('Enter an integer greater than 1: '))

print(chosenInt)

while chosenInt != 1:
    chosenInt = collatz(chosenInt)
    print(chosenInt)

0
def collatz(number):
if (number%2 == 0):
    return print(number//2);
else:
    return (print(number*3+1));

inputNumber = input("Enter a number greater than 1:");
result = collatz(int(inputNumber));
while result != 1:
    result = collatz(result);

我在使用它时遇到了TypeError错误!不知道为什么?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接