2

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
3
  • 1
    don't use list as a variable name. Commented Oct 20, 2012 at 7:05
  • what's wrong with stackoverflow.com/a/12985127/989121? Why do you post the same question twice? Commented Oct 20, 2012 at 9:43
  • was not fully satisfied with the responses from there Commented Oct 22, 2012 at 5:28

4 Answers 4

4
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.

Sign up to request clarification or add additional context in comments.

14 Comments

you should probably put do something else in elif
don't use list as a variable name
When would you need the else?
recursive functions is a bad idea in Python though. There is only a limited recursion depth(although it can be increased/decreased) - loops are always simpler and better.
@Pogo. Aww. Crappy misconstruct.
|
1
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)

Comments

0

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.