1

So im attempting to create a recursion function where it takes each item in the list and sums it up altogether, now I know theres a simple built in function sum(a) but I'm trying to work with nested lists such as this below but I keep getting thrown an error.

def sumList():
    list2 = [1, [2, 3,[4, 5, 6], 7, [8, [9, 10]], 11]]
    newlist = []
    lol = 0
    for i in range (len(list2)):

        if type(list2[i]) == type([]):
            print list2[i], "here"
            for i in range (len(list2[i])):
                lol += (len(list2[i]))



            newlist.append(i[:len(i)+1])


        if len(list2)==0:
            return None
        else:
            print list2[i]
            lol+=list2[i]


    print lol

sumList()

Now I know i've got a lot implemented in the program that I imagine isn't needed, but the error I keep getting is

1
[2, 3, [4, 5, 6], 7, [8, [9, 10]], 11] here


TypeError: object of type 'int' has no len()
MrPorba
  • 59
  • 1
  • 2
  • 6

3 Answers3

1

In general, you could flatten your list of lists and search for min in the flattened list. There are many recipes for flattening. Below is one that I took from here.

import collections

def flatten(iterable):
    for el in iterable:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            yield from flatten(el)
        else:
            yield el

list2 = [2, 3, [4, 5, 6], 7, [8, [9, 10]], 11]

print(list(flatten(list2)))
# [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(sum(flatten(list2)))
# 65
Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294
1
def r_sum(mylist,nsum=0):
    for i in mylist:
        if isinstance(i,int):
            nsum += i
        else:
            nsum += r_sum(i)
    return nsum
user2782067
  • 382
  • 4
  • 19
0
# Python 2.7
def recursiveSum(data):
  # This naively assumes that if it's not an int, it's a list
  # You may want to add more error handling if you expect dirtier data
  if isinstance(data, int): return data
  mySum = 0
  for i in data: mySum += recursiveSum(i)
  return mySum

list2 = [1, [2, 3,[4, 5, 6], 7, [8, [9, 10]], 11]]
print recursiveSum(list2) # Should get 66
rchang
  • 5,150
  • 1
  • 15
  • 25