打印带有collat​​z计数的数字计数:特定问题

时间:2018-11-18 18:27:58

标签: python python-3.x

我写了这段代码,我想找出给定输入整数达到x [n] = 1所需的迭代次数n,并打印该数量。 (顺便说一下,这是collat​​z计数)。代码是:

x0 = int(input('Enter number:'))
while x0 > 1:
    print(x0, end=' ')
    if (x0 % 2):
        x0 = 3*x0 + 1
    else:
        x0 = x0//2

print(1, end=' ')

我想知道答案中有多少个数字,但是有了这段代码,我得到了所有答案。 (输入数字:3给

3 10 5 16 8 4 2 1

但是我希望我的答案看起来像这样:

8

我认为将len()放在print之后是可行的,但没有成功。我该怎么办?

1 个答案:

答案 0 :(得分:1)

只需在您的while循环中添加一个计数器:

x0 = int(input('Enter number:'))
counter = 1    # start at 1 b/c adding 1 after the loop
while x0 > 1:
    # increment so you count how often it loops
    counter += 1
    print(x0, end=' ')
    if (x0 % 2):
        x0 = 3*x0 + 1
    else:
        x0 = x0//2

print(1)  # print the 1 and newline

# and print the count as well
print(counter)

输出:

Enter number:20
20 10 5 16 8 4 2 1
8

您还可以在列表中收集所有数字:

nums = []
while x0 > 1:
    nums.append(x0)
    if (x0 % 2):
        x0 = 3*x0 + 1
    else:
        x0 = x0//2

nums.append(1)

print(*nums)       # print the whole list here
print(len(nums))   # and it's length

琐事:低于1,000,000的最长collat​​z是837799,其中525步距1 && xkcd.com take on Collatz Conjecture-您在wikipedia处找到其他限制