Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...