j: #making x always-6ren">
gpt4 book ai didi

python - 为什么会出现内存错误?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:24 24 4
gpt4 key购买 nike

这是我的代码:

i=int(input("enter your number"))
j=int(input("enter your number"))
if i>j: #making x always greater than y
x=i
y=j
elif i<j:
x=j
y=i
else:
print("invalid")
k=y
cyclelength=[]
while k<=x:
list=[k]
while k!=1:
if(k%2==0):
k=i//2
else:
k=3*k+1
list.append(k)
cyclelength.append(len(list))
k+=1
print(y," ",x," ",max(cyclelength))

我得到以下异常:

Traceback (most recent call last):
File "C:/Python32/uva100.py", line 21, in <module>
list.append(k)
MemoryError

最佳答案

您的意思可能是 k//= 2 而不是 k=i//2

def cyclelength(k):
assert k > 0
count = 1
while k != 1:
k = k // 2 if k % 2 == 0 else 3 * k + 1
count += 1
return count

k_with_max_cyclelength = max(range(y, x+1), key=cyclelength)

或者两者兼得:

k, max_cyclelength = max(((k, cyclelength(k)) for k in range(y, x+1)),
key=lambda pair: pair[1])

关于python - 为什么会出现内存错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11315683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com