首页 > 解决方案 > 代码未输入带有有效语句的 if 语句且未退出 while 循环

问题描述

我试图看看 Collat​​z 猜想是否真的是真的,它说每个整数如果是偶数则除以 2,然后乘以 3,如果奇数则加 1,最终将进入 4、2 的循环, 1. 但它卡在了一个 while 循环中,不会中断或进入我想要的 if 语句

integers = [5]

#Returns true if a number is even and false if it's odd
def even(num):
    if (num % 2 == 0):
        return True
    else:
        return False
#Returns true if a list of a number is in a loop
def loop(numbers):
    for x in numbers:
        if (numbers.count(x) > 1 or 4 in x == True):
            return True
            break
        else:
            return False
            continue

#Print a list of numbers that agree with the Collatz conjecture
def collatz(list):
    for x in list:

        collatz_nums = []
        l = loop(collatz_nums)
        list.append(list[-1] + 1)

        #Add the first number to the "collatz_nums" list
        if (even(x) == True):
            collatz_nums.append(x / 2)
        elif (even(x) == False):
            collatz_nums.append(x * 3 + 1)

        #Adds numbers to the collatz_nums variable
        while (l != True):
            print("Start")
            if (l == False):
                if (even(collatz_nums[-1]) == True):
                    collatz_nums.append(collatz_nums[-1] / 2)
                    print("/2")
                else:
                    collatz_nums.append(collatz_nums[-1] * 3 + 1)
                    print("*3+1")
            else:
                print("Exit")
                break


    print(F'{x} = {collatz_nums}')

collatz(integers)

标签: pythonpython-3.x

解决方案


让我们从这里开始

collatz_nums = []
l = loop(collatz_nums)

如果您有数据要循环,您将一个空列表传递给一个只有 return 语句的函数,因此该函数返回,设置l = None

现在while (None!=True)是一个无限循环,因为您永远不会修改l

也许您应该将“添加第一个数字” if 语句(实际上只需要使用 if-else 调用一次偶数函数)移到这两行之上?或以上,for x in list以便您只添加第一个数字一次?

我还建议删除4 in x == True,因为我怀疑这是否符合您的要求


推荐阅读