【问题标题】:Collatz Equation = Automate the Boring Stuff - Chapter 3Collat​​z 方程 = 自动化无聊的东西 - 第 3 章
【发布时间】:2020-04-28 01:45:32
【问题描述】:

我正在尝试从使用 Python 自动化无聊的东西的第 3 章末尾找到的项目中编写一个 Collat​​z 程序。以下是项目描述:

编写一个名为 collat​​z() 的函数,它有一个名为 number 的参数。如果数字是偶数,那么 collat​​z() 应该打印数字 // 2 并返回这个值。如果数字是奇数,则 collat​​z() 应该打印并返回 3 * number + 1。然后编写一个程序,让用户输入一个整数,并在该数字上不断调用 collat​​z(),直到函数返回值 1。

此程序的输出可能如下所示:

输入号码:3 10 5 16 8 4 2 1

问题:为什么我在输入整数时会陷入无限循环?无论我读了多少次关于 while 循环的内容,我似乎都无法摆脱这种状态。有人可以解释一下我如何让程序在第一次运行 collat​​z 函数时使用结果一次又一次地运行 collat​​z 函数?

def collatz(number):
    if number % 2 == 0:
        print(number//2)
        return number//2

    elif number % 2 != 0:
        print(3 * number + 1)
        return 3 * number + 1

while True:
    print('Enter integer: ')
    digit = int(input())
    while digit > 1:
        collatz(digit)
        if collatz(digit) == 1:
            print('This is the end of the collatz test.')
            break
    if digit < 0:
        print('This is an error. Please try again')

【问题讨论】:

    标签: python


    【解决方案1】:

    collatz() 函数返回一个新数字,但在您的 while 循环中,您没有对它返回的数字做任何事情。这意味着collatz()返回的数字立即被丢弃,而digit的值在用户输入后永远不会改变。

    while True:
        print('Enter integer: ')
        digit = int(input())
        while digit > 1:  # Nothing inside the loop changes this value
            collatz(digit)  # This function's return value is ignored
            if collatz(digit) == 1:
                print('This is the end of the collatz test.')
                break
    

    如果您每次都更新 digit 的值,循环将起作用,直到该值最终等于 1:

    while True:
        print('Enter integer: ')
        digit = int(input())
        while digit > 1:
            digit = collatz(digit)  # Digit is now different each iteration
            if digit == 1:  # No need to call the function a second time
                print('This is the end of the collatz test.')
                break
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多