如何计算使用 python 打印了多少次数字?

How to count how many times a number was printed using python?

所以我做了一个nooby Collat​​z Sequence展示程序。我很想知道计算机打印了多少次number,这样我就可以看到一个数字最终变成1需要多少步。如果你对Collat​​z序列不太了解,运行 我的代码...

import sys

def collatz(number):

    if number <= 0:
        print("Next time, enter an integer greater than 1.")
        sys.exit()

    while number % 2 == 0:
        number = number // 2
        print(number)

    if number == 1:
        sys.exit()

    while number % 2 != 0:
        number = 3*number+1
        print(number)
        collatz(number)


print("""Enter a number.
Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.
This is called as Collatz sequence.
Watch as your number slowly becomes 1.
Enter a positive integer:""")
try:
    collatz(int(input()))
except ValueError:
    print("Next time, Enter a positive integer, you dummy...")

一个非常快速和肮脏的方法来做到这一点,就是使用“迭代”参数。这样的事情会得到你想要的结果:

import sys    
def collatz(number, iterations=0):
    
        if number <= 0:
            print("Next time, enter an integer greater than 1.")
            sys.exit()
    
        while number % 2 == 0:
            number = number // 2
            print(number)
            iterations += 1
    
        if number == 1:
            print(f'This number took {iterations} steps to get to 1')
            sys.exit()
    
        while number % 2 != 0:
            number = 3*number+1
            print(number)
            iterations += 1
            collatz(number, iterations)
    
    
    print("Enter a number.")
    print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
    print("This is called as Collatz sequence.")
    print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
    try:
        collatz(int(input()))
    except ValueError:
        print("Next time, Enter a positive integer, you dummy...")

您也可以使用全局变量steps。不过NewBoard的方案也不错

import sys

steps = 0

def collatz(number):
    global steps

    if number <= 0:
        print("Next time, enter an integer greater than 1.")
        sys.exit()

    while number % 2 == 0:
        steps += 1
        number = number // 2
        print(number)

    if number == 1:
        print(f"Steps: {steps}")
        sys.exit()

    while number % 2 != 0:
        steps += 1
        number = 3*number+1
        print(number)
        collatz(number)


print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
    collatz(int(input()))
except ValueError:
    print("Next time, Enter a positive integer, you dummy...")