1

这是我的代码:

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
4

4 回答 4

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])
于 2012-07-03T17:08:26.243 回答
2

此块中的另一个问题:

while k!=1:
    if(k%2==0):
        k //= 2
    else:
        k=3*k+1

退出时 k 的值为 1。

所以你将 k 增加到 2,重新输入 while,因为 k < x 并将 k 重置为 1

--> 无限循环

你必须在你的内部定义一个新变量,或者在另一个函数中提取这个块

于 2012-07-03T17:08:37.070 回答
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
于 2012-07-03T17:11:17.860 回答
0

这看起来像是在玩Collat​​z 猜想。尝试

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()
于 2012-07-03T17:25:59.050 回答