这是我的代码:
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
答案 0 :(得分:5)
您可能需要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])
答案 1 :(得分:2)
此块中的另一个问题:
while k!=1:
if(k%2==0):
k //= 2
else:
k=3*k+1
退出时,k的值为1。
所以你将k增加到2,重新输入while,因为k&lt; x并将k重置为1
- &GT;无限循环
你必须在内部定义一个新变量,或者在另一个函数中提取这个块
答案 2 :(得分:0)
我认为你要去
n=y
cyclelength=[]
while n<=x:
k=n
list=[k]
while k!=1:
if(k%2==0):
k//=2
else:
k=3*k+1
list.append(k)
cyclelength.append(len(list))
n+=1
答案 3 :(得分:0)
这看起来像是在玩Collatz conjecture。尝试
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def sequence_length(k):
length = 0
while k > 1:
k = 3*k+1 if k&1 else k//2
length += 1
return length
def max_sequence_length(lo, hi):
best_k, best_length = None, 0
for k in xrange(lo, hi+1):
length = sequence_length(k)
if length > best_length:
best_k, best_length = k, length
return best_k, best_length
def main():
lo = get_int("Enter the start number: ")
hi = get_int("Enter the finish number: ")
lo, hi = min(lo, hi), max(lo, hi)
best_k, best_length = max_sequence_length(lo, hi)
print("In {}..{}, max cycle length is {} at k = {}".format(lo, hi, best_length, best_k))
if __name__=="__main__":
main()