Rahul Sharma
Rahul Sharma

Reputation: 1169

How do I turn a while loop into a recursive method?

I need help turning this while loop into a recursive method? How do I do this?

while z <= len(list):
     if z = len(list): #base case
        return something
     else:
        #do something else
     z += 1

Upvotes: 2

Views: 12894

Answers (4)

John Forbes
John Forbes

Reputation: 1354

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

Upvotes: 0

Akash Rajpuria
Akash Rajpuria

Reputation: 21

I will implement the recursive function using while loop ---Factorial----
(1)It will call the fact function recursively based on while condition
(2)You can add if or nested if according to your problem statement

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

result = fact(3)
print(result)

6

Upvotes: 0

pogo
pogo

Reputation: 1550

z = 1

while z <=5:
    if z == 5:
        print 'base case'
    else:
        print 'repeated text'
    z += 1

This is translated to recursive code as follows. You can work on your case based on this

def recursion(z):
    assert z <= 5
    if z == 5:
        print 'base case'
    else:
        print 'repeated text'
        recursion(z+1)

recursion(1)

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213311

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)    

You should not use list as variable name.

Upvotes: 4

Related Questions