python - 代码未输入带有有效语句的 if 语句且未退出 while 循环
问题描述
我试图看看 Collatz 猜想是否真的是真的,它说每个整数如果是偶数则除以 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)
解决方案
让我们从这里开始
collatz_nums = []
l = loop(collatz_nums)
如果您有数据要循环,您将一个空列表传递给一个只有 return 语句的函数,因此该函数返回,设置l = None
现在while (None!=True)
是一个无限循环,因为您永远不会修改l
也许您应该将“添加第一个数字” if 语句(实际上只需要使用 if-else 调用一次偶数函数)移到这两行之上?或以上,for x in list
以便您只添加第一个数字一次?
我还建议删除4 in x == True
,因为我怀疑这是否符合您的要求
推荐阅读
- java - 追踪继承关系?
- c - C Accept Client Socket "Invalid Argument" Error when adding Signal Thread
- java - 从 BDDMockito 中删除实体
- c++ - 我在这里如何滥用 C++ 承诺和期货?
- python-2.7 - 使用 saltstack 如何编写自定义信标
- python - Python / SQL未将连接的数据库显示到表
- node.js - QuerySnapshot.docChanges 已从属性更改为方法
- java - 通过 REST 连接到 SharePoint 2016 - 空响应?
- python - 沿特定轴添加/相乘张量和矢量
- javascript - 数据数组将行值列表塞进一个对象中