0

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, lst=[]):
        self.lst = lst

    def add(self, x, y):
        return x + y

    def recurs(self):
        if len(self.lst) == 1:
            return lst[0]
        else:
            return self.lst[0].add(self.recurs(lst[1:])
5
  • 1
    What is the code supposed to do exactly? Commented May 11, 2012 at 5:53
  • 2
    Why do you have an add method on the class? Commented May 11, 2012 at 5:53
  • @Patrick also why don't you just use sum instead of making your own add method. Commented May 11, 2012 at 6:02
  • @jamylak I think @Omerta is practicing recursion for an exam. Otherwise, using sum would be the way to go. Commented May 11, 2012 at 6:06
  • @Oliver I thought the add method just added numbers, nvm misread it then. Commented May 11, 2012 at 6:07

3 Answers 3

4

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) ) = ...

class recursive_summer:
    def __init__(self, lst=[]):
        self.lst = lst
    def recursive_sum(self):
        return self.recursive_sum_helper(self.lst)
    def recursive_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.

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

Comments

1

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

it uses pop method from list

class rec(object):
    def __init__(self):
        self.sum = 0

    def recur(self, list):
        if len(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

Comments

0

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

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

3 Comments

If the question says recursion as the 2nd word, you shouldn't post this as an answer.
it's not actually answer, but it's may be helpful info for exam preparation
it really should be a comment then but you don't have enough rep to comment on the question so never mind.

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.