我目前正在学习Python,我正在尝试完成练习。练习要求我:
到目前为止,我的代码完成了前两个操作,但我正在努力实现循环,这将继续重新运行计算,直到答案为1.这是我的代码到目前为止:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at check.main(check.java:6)
答案 0 :(得分:3)
使用while
loop:
def collatz(number):
print(number)
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
或者,您可以使用递归:
def collatz(number):
print(number)
if number == 1:
return
collatz(number // 2 if number % 2 == 0 else number * 3 + 1)
答案 1 :(得分:1)
def collatz(n):
print n
if n == 1:
return
if n % 2 == 0:
n2 = (n / 2)
elif n % 2 == 1:
n2 = (3 * n + 1)
collatz(n2)
print('Please write a number')
number = collatz(int(input()))