Skip to content Skip to sidebar Skip to footer

Using Recursion In A Class

I'm practicing for an exam and trying to figure this out. I'm just not exactly what to do with the add method. This is what I have so far: class recursion: def __init__(self, l

Solution 1:

Assuming you're trying to recursively get the sum of the list:

Essentially, recursive_sum_helper keeps calling itself with smaller lists:

sum(1, 2, 3, 4) = 1+sum(2,3,4) = 1+( 2 + sum(3,4) ) = ...

classrecursive_summer:def__init__(self, lst=[]):
        self.lst = lst
    defrecursive_sum(self):
        returnself.recursive_sum_helper(self.lst)
    defrecursive_sum_helper(self, a_lst):
        if len(a_lst) == 1:
            return a_lst[0]
        else:
            first_element = a_lst[0]
            list_without_first_element = a_lst[1:]
            return first_element + self.recursive_sum_helper( list_without_first_element )

r = recursive_summer([1,2,3,4])
r.recursive_sum()

The output is 10.

Hope this helps with whatever problem you're trying to solve.

Solution 2:

it's recursion way to do this, but more clean:

it uses pop method from list

classrec(object):
    def__init__(self):
        self.sum = 0defrecur(self, list):
        iflen(list) > 0:
            self.sum += list.pop()
            self.recur(list)
        else:
            return self.sum

using:

>>>from code import rec>>>a = rec()>>>b = [1,2,3]>>>print a.recur(b)
6

Solution 3:

another way to get sum of the list without recursion, but more faster and effective:

>>>a = [1,2,3]>>>sum(a)
6
>>>

Post a Comment for "Using Recursion In A Class"