Find the sum of nested list using recursion
lst = [1,2,[3,4],[5,6]]
def findSum(values,sum,idx):
if len(values) == idx:
return sum
if isinstance(values[idx],list):
return findSum(values[idx],sum,0)
else:
sum = sum + values[idx]
return findSum(values,sum,idx+1)
print(findSum(lst,0,0))
Output should be 21
but I am getting only 10
last index subarray([5,6]) not getting calculated.
Can anyone suggest me, what I am doing wrong in the logic?
You can recurse through the list as shown below
def recur_sum(lst):
s = 0
for x in lst:
if type(x) == list:
s += recur_sum(x)
else:
s += x
return s
lst = [1,2,[3,4],[5,6]]
print(recur_sum(lst))
EDIT: The problem with OP's code is, the code is not moving forward after its done processing a sublist and returns from there.
There are just some good pointers earlier about the origin codes problem, so I am not going to repeat here.
This is just a simpler approach for this problem, maybe as a reference.
A = [1, 2, [3, 4], [5,6]]
def sum_lst(A):
total = 0
for x in A:
if isinstance(x, list):
total += sum_lst(x)
else:
total += x
return total
print(sum_lst(A)) # 21
Just for fun: a recursive approach using reduce
.
A (mathematical) recursion is defined by an initial value and a relationship between a certain terms and its previous ones. The initial value can be specified by the initializer
parameter of reduce
and, in this case, it is set to 0
. The recursive function can be passed as a parameter to reduce
.
Notice:
for
-loop is requiredfrom functools import reduce
def recursive_relationship(i, j):
if isinstance(j, list):
if j:
return recursive_relationship(i+j[0], j[1:])
else:
return i
return i + j
lst = [1,2,[3,4],[5,6], [8]]
#lst = [[1, 2], [1, 2,3], [1]]
print(reduce(recursive_relationship, lst, 0))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.