背景:
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)

本文介绍了一个使用Python实现的Collatz序列计算程序。该程序通过定义一个collatz函数来处理输入的整数n,根据n的奇偶性计算n//2或3*n+1,并不断迭代直至n变为1,输出每次迭代的结果。
864

被折叠的 条评论
为什么被折叠?



