Heyya
Heyya

Reputation: 193

Trouble converting for loop into recursive function in python

I am trying to write a program that finds the max sum of nonadjacent elements in a 1 dimensional array and so far I have this:

def find_max_sum(arr):
    incl = 0
    excl = 0

    for i in arr:

        # Current max excluding i 
        new_excl = excl if excl>incl else incl

        # Current max including i
        incl = excl + i
        excl = new_excl

    # return max of incl and excl
    return (excl if excl>incl else incl)

It works. My only question is how would one go about transforming this function into a recursive function without using the for loops? My brain can't seem to find a way to do this.

Upvotes: 2

Views: 112

Answers (1)

Elmex80s
Elmex80s

Reputation: 3504

Step 1: rewrite your function so it is more Pythonic

def find_max_sum(lst):
    incl, excl = 0, 0

    for i in lst:
        incl, excl = excl + i, max(excl, incl)

    return max(excl, incl)

Step 2: now it is easy to rewrite it to a recursive function

def find_max_sum_recursive(lst, incl, excl):        
    if len(lst) > 0:
        i = lst[0]
        incl, excl = excl + i, max(excl, incl)

        return find_max_sum_recursive(lst[1:], incl, excl)
    else:
        return incl, excl

def call_find_max_sum_recursive(lst):
    return max(find_max_sum_recursive(lst, 0, 0))

Now you call

>>> call_find_max_sum_recursive([1, 2, 10, 3, 4])
15

Step 1 is not absolutely necessary. After all it is about the block of code in your for i in arr: and how they affect incl and excl. However it might help you rewriting.

Upvotes: 2

Related Questions