You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Collatz序列时输出重复问题求助

Collatz序列输出重复问题解决

我正在尝试用Python实现Collatz序列的输出,大致功能已实现,但输出中存在重复值。即便对比无重复输出的代码,仍无法找到解决方法。我学习Python约1个月,这是我首个涉及函数的练习程序,提前感谢帮助!

我的代码

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

print('Enter a number:')
inputValue = int(input())
while inputValue != 1:
    collatz(inputValue)
    inputValue = collatz(inputValue)

当前输出

Enter a number:
5
16
16
8
8
4
4
2
2
1
1

期望输出

Enter number:
5
16
8
4
2
1

问题原因与解决方法

问题出在while循环里,你每次循环会执行两次collatz函数调用:

  • 第一次单独调用collatz(inputValue)时,函数内部已经打印了计算结果;
  • 第二次赋值inputValue = collatz(inputValue)时,又会调用一次函数,再次打印相同的结果,这就导致了输出重复。

只需要删除循环里单独的collatz(inputValue)调用,保留赋值那一行即可:

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

print('Enter a number:')
inputValue = int(input())
while inputValue != 1:
    inputValue = collatz(inputValue)

这样修改后,每次循环只会调用一次collatz函数,打印一次结果,就能得到你期望的输出。

内容的提问来源于stack exchange,提问作者soofy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:35:25