Collatz序列的Python实现

    xiaoxiao2021-03-25  79

    背景:

    Automate the boring stuff with python(Written by Al Sweigart.)一书的Chapter 3 – Functions关于函数的论述中,末尾有一个计算Collatz序列的实践项目,具体要求为:

    输入一个整数n,提供一个函数collatz(n)对n进行计算,规则为:若n是一个偶数则计算n//2(n整除2)的结果若是奇数则计算3*n+1作为结果每次计算的结果再拿来视为n重新做collatz(n)计算,直到计算结果为1为止。把每次计算的结果显示出来,这就是所谓的Collatz序列。

    以下是Python的代码:

    # Give a number to process while True: try: print('Enter an integer number:') n = int(input()) break except: print('You gave a noninteger string.') # set function to process n def collatz(number): r = number % 2 if r == 0: return number // 2 else: return 3 * number + 1 # while-loop to display the results while n !=1: print(collatz(n)) n = collatz(n)
    转载请注明原文地址: https://ju.6miu.com/read-14909.html

    最新回复(0)