collat​​z序列infinte循环错误

时间:2017-09-28 04:34:31

标签: python-3.x collatz

我得到一个无限循环。我不确定如何将结果转换为新的数字变量并将其放回while循环中。

#Collatz squence

import sys
def collatz():
    try:
         print('Enter a number')
         number = int(input())
    except:
        ValueError
        print('Please type an integer')

    while number != 1:
        if number %2 == 0:
            result = number//2

            print(result)

        elif number %2 == 1:

            result = 3*number + 1

            print(result)

        **result = number**


    while number == 1:
        print ('You have arrived at the number itself')
        sys.exit()

collatz()

1 个答案:

答案 0 :(得分:0)

以下作品:

#Collatz squence

import sys
def collatz():
    try:
         print('Enter a number')
         number = int(input())
    except ValueError:
        print('Please type an integer')
        sys.exit(1)

    while number != 1:
        if number %2 == 0:
            result = number//2
            print(result)

    elif number %2 == 1:
        result = 3*number + 1
        print(result)
    number = result # set the number to the result

    while number == 1:
        print ('You have arrived at the number itself')
        sys.exit()

collatz()

请注意,我将数字设置为结果,在代码中数字永远不会改变,因此一遍又一遍地使用相同的代码块。我还在异常中添加了一个sys.exit调用,如果有人输入了错误值,我们不想继续。