Python: The Collatz Sequence

本文介绍了一个基于Python的程序,该程序实现了Collatz序列。通过定义Collatz函数,如果输入的数字为偶数,则输出数字除以2;如果是奇数,则输出3倍数字加1。程序会持续调用此函数直到返回值为1。用户可以输入任意整数开始这一序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习《Python编程快速上手》P56

问题链接:https://automatetheboringstuff.com/chapter3/

     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. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. 

    Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)  Remember to convert the return value from input() to an integer with the int()  function; otherwise, it will be a string value.

代码实现:

# Problem: The Collatz Sequence
# The url of the problem: https://automatetheboringstuff.com/chapter3/

# Define the function
def Collatz(number):
    if number % 2 == 0:
        return number//2
    elif number % 2 == 1:
        return 3*number+1
        
# Enter an integer        
try:
    Num = int(input('Enter a number:\n'))
    
    # Call the Collatz.
    while True:
        Result = Collatz(Num)
        print(Result)
    
        if Result == 1:
            break
        
        Num = Result
    
except ValueError:
    print('You need enter an integer!')

运行示例:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值