Python 试图;“中断”;Collatz猜想并生成3n-1序列(将有循环)
这就是我到目前为止所做的:Python 试图;“中断”;Collatz猜想并生成3n-1序列(将有循环),python,math,Python,Math,这就是我到目前为止所做的: def collatz_sequence(x): seq = [x] if x < 1: return [] y = x*2 while x != 1 and x != y: if x % 2 == 0: x = x / 2 else: x = 3 * x - 1
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
y = x*2
while x != 1 and x != y:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x - 1
seq.append(x) # Added line
return seq
x = 5
while x < 10:
print collatz_sequence(x)
x += 1
def collatz_序列(x):
seq=[x]
如果x<1:
返回[]
y=x*2
而x!=1和x!=y:
如果x%2==0:
x=x/2
其他:
x=3*x-1
seq.追加(x)#增加行
返回顺序
x=5
当x<10时:
打印拼贴顺序(x)
x+=1
因此,它在三种情况中有两种情况下停止:它实际工作并返回到1,它不工作并返回到自身(5->14->7->20->10->5)。如果它基本上进入另一个循环,例如(9->26->13->35->104->52->26),它不会停止
如何遍历每个循环末尾的序列,并在序列中重复一个整数时使其停止?(我想我可以去掉while语句中的x!=y部分来执行此操作)。您可以在seq:操作中使用
if x
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
y = x*2
while x != 1 and x != y:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x - 1
if x in seq:
seq.append(x) # Add at end of list so you can see the loop in output
break
seq.append(x) # Added line
return seq
x = 5
while x < 20:
print collatz_sequence(x)
x += 1
def collatz_序列(x):
seq=[x]
如果x<1:
返回[]
y=x*2
而x!=1和x!=y:
如果x%2==0:
x=x/2
其他:
x=3*x-1
如果序列中有x:
seq.append(x)#在列表末尾添加,以便您可以在输出中看到循环
打破
seq.追加(x)#增加行
返回顺序
x=5
当x<20时:
打印拼贴顺序(x)
x+=1
当您测试x是否在序列中时,需要特别小心,因为您需要确保在添加项之前进行测试。
我不确定y
变量用于什么函数。Collatz猜想使用3n+1
,而不是3n-1
。我知道。我想用3n-1来代替,看看循环是什么样子。所以我说“打破”它。对不起,不清楚。可能有用。或者你可以用一套。