python - Collat​​z 序列以 4 结束

标签 python python-3.x

我正在使用《用Python自动化无聊的事情》第3章中的实践项目编写一个Collat​​z序列程序。

计划大纲是:

Write a function named collatz() that has one parameter named number.

If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.

Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.

我的代码运行,但它停止在 4 而不是 1。到目前为止,对于我尝试过的每个数字,输出都会从 1 回到 4。

示例输出:

6,3,10,5,16,8,4,2,1,4

我使用的是python 3.4.2

def collatz(number):
    if number % 2 == 0:
        number = number //2
        print(number)
        return number
    elif number % 2 == 1:
        number = 3 * number + 1
        print(number)
        return number


print ("pick a number:")

while True:
try:
    number = int(input())
    while number != 1:
            number = collatz(number)
    collatz(number)
    break
except ValueError:
        print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")

最佳答案

问题是你在循环结束后再次调用 collat​​z() 1。只需删除该行,它就可以正常工作。

此外,如果您将“选择一个数字” 移至 input 函数,则可以避免问题后出现新行,并且每次都会再次询问,如果您输入无效值。

此外,您还应该检查数字是否大于或等于 1,以避免无限循环。执行所有操作的代码如下所示:

while True:
    try:
        number = int(input("pick a number: "))
        if number < 1:
            print("Error: Please enter a integer greater than or equal to 1 ")
            continue

        while number != 1:
                number = collatz(number)
        # removed the additional call to collatz
        break
    except ValueError:
            print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")

关于python - Collat​​z 序列以 4 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884792/

相关文章:

python - 使用 MultiEncoder,我有一个数组 encoders[],我想知道编码器接受什么数据类型。这怎么可能?

python - 使用plot在matplotlib中将二维二进制矩阵绘制为一条线?

python - Pandas+seaborn 多维数据框分面

python - 在 python 中使用 BeautifulSoup 进行标签和字符串混合查找和替换

python - Python 3.8.5 cv2 -215:断言失败

python-3.x - 使用 boto3 获取给定 EC2 实例类型的当前价格

python - 简单的 Python 温度转换器

python - 使用python登录网站并上传文件

python - bool 类型的 Argparse

python - F1 分数指标和分类报告 sklearn 的 F1 分数值不同