我需要帮助将此 while 循环转换为递归方法吗?我该怎么做呢?
while z <= len(list):
if z = len(list): #base case
return something
else:
#do something else
z += 1
我需要帮助将此 while 循环转换为递归方法吗?我该怎么做呢?
while z <= len(list):
if z = len(list): #base case
return something
else:
#do something else
z += 1
def func(my_list, z):
if z == len(my_list):
return something
else:
# do something else
return func(my_list, z+1)
z = someValue
print func(my_list, z)
您不应该list
用作变量名。
z = 1
while z <=5:
if z == 5:
print 'base case'
else:
print 'repeated text'
z += 1
这被转换为递归代码,如下所示。您可以基于此处理您的案例
def recursion(z):
assert z <= 5
if z == 5:
print 'base case'
else:
print 'repeated text'
recursion(z+1)
recursion(1)
condition = lambda n: n >= 3
repetition = lambda n: print(f'{n}: Repeating Line')
termination = lambda n: print(f'{n}: Terminal Line')
def recursive(n):
if condition(n):
repetition(n)
n = recursive(n-1)
else:
termination(n)
return n
def iterative(n):
while condition(n):
repetition(n)
n -= 1
termination(n)
return n
def main():
n = 4
print("Recursion Example")
result = recursive(n)
print(f'result = {result}')
print()
print("Iteration Example")
result = iterative(n)
print(f'result = {result}')
print()
main()
>>> Recursion Example
>>> 4: Repeating Line
>>> 3: Repeating Line
>>> 2: Terminal Line
>>> result = 2
>>>
>>> Iteration Example
>>> 4: Repeating Line
>>> 3: Repeating Line
>>> 2: Terminal Line
>>> result = 2
我将使用while循环实现递归函数---Factorial----
(1)它将基于while条件递归调用事实函数
(2)您可以根据您的问题陈述添加if或嵌套if
def fact(num):
while num>1:
return num*fact(num-1)
else:
return num
result = fact(3)
print(result)
6