Hi! I just finished the recursion chapter on the CS with Python skill path and just trying to get some practice with some online -quite basic- problems.
On this one, i have to find the sum of the elements in a list, and some elements of the list are lists themselves.
This is where I got:
def sum_lst_rec(lst, lst_sum = 0): if len(lst) == 0: return lst_sum if isinstance(lst, list): sub_lst = lst if len(sub_lst) == 0: return sum_lst_rec(lst[1:], lst_sum) lst_sum += sub_lst return sum_lst_rec(sub_lst[1:], lst_sum) lst_sum += lst return sum_lst_rec(lst[1:], lst_sum) test_lst_2 = [1, 2, [3,4], [5, 6]] print(sum_lst_rec(test_lst_2))
The code runs, but only sums until it encounters the first element that is a list. It sums the elements in that list, but doesn’t go on with the recursion. In this example, it returns
What am I missing?!