簡體   English   中英

如何將 while 循環轉換為遞歸方法?

[英]How do I turn a while loop into a recursive method?

我需要幫助將這個 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)

我將使用 while 循環實現遞歸函數 ---Factorial----
(1)會根據while條件遞歸調用fact函數
(2)你可以根據你的問題陳述添加if或nested if

def fact(num):
    while num>1:
        return num*fact(num-1)
    else:
        return num

result = fact(3)
print(result)

6個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM