递归函数 python 3 'maximum recursion depth exceeded'
recursive function python 3 'maximum recursion depth exceeded'
我正在用下面的递归函数创建一个 collatz 序列:
def collatz(n):
if n%2 == 0:
return int(n/2)
else:
return int((3 * n)/2)
据我了解,递归函数基本上是调用自身的函数。下面我尝试使用以下内容创建递归函数:
def collatz(x):
if x == 1:
"Done"
print(x)
x = collatz(x)
return(x)
基本上变量 x 继续传递到我定义的 collatz
函数中,直到它变为 1。但是,每次我 运行 它打印的递归函数 'x'
反复然后我得到
collatz(3)
'RecursionError: maximum recursion depth exceeded in comparison'
我理解的本质上是一个无限循环。我想通过将它重新分配给 x
到第一个 collatz()
的结果,它将 return 新值并继续直到它达到 '1'
但我似乎不能完全到达那里。
任何 help/tips/advice 都很棒!谢谢!
递归函数有所谓的 "base case" 和 "recursive case." 基本情况是你应该 停止 递归和 return一个答案。
在这种情况下,基本情况是 x==1
def collatz(x):
if x == 1:
return x
而递归的情况就是剩下的时间
# continuing from above
else:
if n % 2 == 0:
return collatz(int(n//2))
else:
return collatz(n*3 / 2) # sicut. Note that the collatz sequence
# uses 3n+1 here, not 3n/2 as in the question
N.B。在 returning 那个新调用的结果之前,我在 collatz
的下一个循环中更改了 x
的有效值。如果你不这样做,并且只是 return collatz(x)
,你将永远无法达到你的基本情况并永远递归。
您展示了同一函数 collatz 的两个不同实现,而您需要将它们组合起来。
def collatz(n):
if x == 1:
"Done"
print(x)
if n%2 == 0:
collatz(int(n/2))
else:
collatz(int((3 * n)/2))
@Roee Gavirel
这是根据他上面的回答得出的最终答案:
def collatz(x):
if x == 1:
"Done"
elif x%2 == 0:
x = int(x/2)
print(x)
collatz(x)
else:
x = int((3*x)+1)
print(x)
collatz(x)
collatz(3)
感谢大家的帮助!
我正在用下面的递归函数创建一个 collatz 序列:
def collatz(n):
if n%2 == 0:
return int(n/2)
else:
return int((3 * n)/2)
据我了解,递归函数基本上是调用自身的函数。下面我尝试使用以下内容创建递归函数:
def collatz(x):
if x == 1:
"Done"
print(x)
x = collatz(x)
return(x)
基本上变量 x 继续传递到我定义的 collatz
函数中,直到它变为 1。但是,每次我 运行 它打印的递归函数 'x'
反复然后我得到
collatz(3)
'RecursionError: maximum recursion depth exceeded in comparison'
我理解的本质上是一个无限循环。我想通过将它重新分配给 x
到第一个 collatz()
的结果,它将 return 新值并继续直到它达到 '1'
但我似乎不能完全到达那里。
任何 help/tips/advice 都很棒!谢谢!
递归函数有所谓的 "base case" 和 "recursive case." 基本情况是你应该 停止 递归和 return一个答案。
在这种情况下,基本情况是 x==1
def collatz(x):
if x == 1:
return x
而递归的情况就是剩下的时间
# continuing from above
else:
if n % 2 == 0:
return collatz(int(n//2))
else:
return collatz(n*3 / 2) # sicut. Note that the collatz sequence
# uses 3n+1 here, not 3n/2 as in the question
N.B。在 returning 那个新调用的结果之前,我在 collatz
的下一个循环中更改了 x
的有效值。如果你不这样做,并且只是 return collatz(x)
,你将永远无法达到你的基本情况并永远递归。
您展示了同一函数 collatz 的两个不同实现,而您需要将它们组合起来。
def collatz(n):
if x == 1:
"Done"
print(x)
if n%2 == 0:
collatz(int(n/2))
else:
collatz(int((3 * n)/2))
@Roee Gavirel
这是根据他上面的回答得出的最终答案:
def collatz(x):
if x == 1:
"Done"
elif x%2 == 0:
x = int(x/2)
print(x)
collatz(x)
else:
x = int((3*x)+1)
print(x)
collatz(x)
collatz(3)
感谢大家的帮助!