Skip to content Skip to sidebar Skip to footer

How Do I Convert A For Loop To A Recursive Method?

Currently, I implement a for loop as a recursive method. for i in range(len(list)): **implementation code goes here** how do I implement this as a recursive method? I am planni

Solution 1:

The standard structural recursive formula (and the one you'd use if you were using a functional language like Scheme) would be to deconstruct the list recursively:

func([]) => nothing
func([x, ...]) => do_stuff(x), func([...])

Therefore, the "functional" way to do this would be to take a single list (not an index), and to recurse on smaller lists:

def rec_list(l):
    if not l: return # empty list case
    # process l[0]
    return rec_list(l[1:])

Note that this is terribly, terribly inefficient because of the l[1:], but it's the basis for understanding more complex recursive constructs (e.g. recursing on binary trees).

We can do interesting things with this kind of structural recursion. For example, here's how you'd reverse a list in a functional language:

def rev_list(l):
    if not l: return []
    return rev_list(l[1:]) + [l[0]]

(Of course, you could just do l[::-1] in Python, but here we're trying to show how it would be done recursively).


Solution 2:

So you want to do away with a nice (mostly) well coded loop? (mostly because you probably want to use enumerate instead of range(len(lst))) -- enumerate is pretty cool, once you start using it, you'll never look back.

Anyway, I guess we can do that:

def silly_loop(lst,index=0):
    try:
       #do something with index and lst here
       silly_loop(lst,index=index+1)
    except IndexError:  #or maybe a different error, depending on what you're doing with index ...
       return

an example:

def silly_loop(lst,index=0):
    try:
       print lst[index]
       silly_loop(lst,index=index+1)
    except IndexError:
       return

a = range(10)
silly_loop(a)

Note that I can't think of ANY reason why you would want to do this in real code, (But, if you're just doing this to teach yourself about recursion, then I hope this helps).


Post a Comment for "How Do I Convert A For Loop To A Recursive Method?"