两个或两个以上数字的单独数字打印

2024-09-30 01:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我制作了一个collatz计算器(如果你不知道它是什么,请查阅),我想记录达到1所需的步骤,然后将数据放入列表中。当一个数字超过2位时,它会在列表中将这些数字分成两个不同的点

这是密码

steps = 0
stepsList = []
numList = []
listCount = 0

while True:
    numIn = int(input('enter number: '))
    while True:
        if numIn % 2 == 0:
            numIn = numIn / 2
        else:
            numIn = (3 * numIn) + 1
        print(numIn)
        steps += 1
        if numIn == 1:
            numIn += 1
            print('~~~')
            print(str(steps) + ' steps')
            stepsList.extend(str(steps))
            print(stepsList)
            break

假设我输入数字27,而不是将其存储为[111],它将其存储为[1,1,1]


Tags: 数据true列表if记录步骤数字steps
2条回答
stepsList = []

while True:
    try:
        numIn = int(input('enter number: '))
    except KeyboardInterrupt:
        break

    steps = 0

    while True:
        if numIn % 2 == 0:
            numIn = numIn / 2
        else:
            numIn = (3 * numIn) + 1
        # print(numIn)
        steps += 1
        if numIn == 1:
            numIn += 1
            print('~~~')
            print(str(steps) + ' steps')
            stepsList.append(steps)
            print(stepsList)
            break

增加了一些清洁和清洁;更好的ctrl-c处理:)

我觉得不错

enter number: 27
~~~
111 steps
[111]
enter number: 1
~~~
3 steps
[111, 3]
enter number: 4
~~~
2 steps
[111, 3, 2]
enter number: 6
~~~
8 steps
[111, 3, 2, 8]
enter number: 10
~~~
6 steps
[111, 3, 2, 8, 6]
enter number: ^C%

只需替换以下行:

            print(str(steps) + ' steps')
            stepsList.extend(str(steps))

            print(steps, 'steps')
            stepsList.append(steps)

如果您需要每个不同测试编号的步数,而不是累积计数器,那么您也应该在外部循环开始时重置steps计数器

相关问题 更多 >

    热门问题