Using recursion in a class

I train on an exam and try to figure it out. I just don’t quite understand 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:]) 
0
source share
3 answers

Assuming you are trying to recursively get the list sum:

Essentially, recursive_sum_helper continues to call itself 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 any problem you are trying to solve.

+4
source

this is a recursive way to do this, but cleaner:

he uses the pop method from the 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 

via:

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

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

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

Source: https://habr.com/ru/post/1412932/


All Articles