1

I'm trying to create a method that will count all the items in a nested list. So count([[3, 2] , [2]]) == 3. However, it's a Class attribute so I can't just simply do:

def count(L, target):
    s = 0
    for i in L: 
        if isinstance(i, list): 
            s += count(i, target)
        else: 
            if i == target: 
                s += 1

    return s 

Rather, I tried to do this, but I get a max recursion depth error. I'm not sure why. Before you look at the code, there's a few things to keep in mind: (1) I expect the base list given to only contain lists so it will have the format: [ [], ]. Also (2) the sub lists will not contain anything except items: [ [item, item], [item] ] :

def count(self, stack=None):
    n = 0
    if stack:
        n += len(stack)
    else:
        for i in self._items:
            if isinstance(i, list):
                n += self.count(i)

    return n

2 Answers 2

2
    if stack:

Empty lists are considered false in a boolean context. You want if stack is not None.

Why use recursion, though? You don't need it.

def count(self):
    return sum(len(item) for item in self._items)
Sign up to request clarification or add additional context in comments.

1 Comment

Lmao ... this is what happens when I learn a new concept and try to apply it to everything. What an easy solution. I appreciate you knocking my head back into gear :P
0

If your lists are only nested one level deep, this is easy.

class MyClass:
    def __init__(self, items):
        self.items = items

    def count(self):
        return sum(len(x) for x in self.items)

a = MyClass([[3,2],[2]])
b = MyClass([[1,2,3],[4,5,6],[7],[]])
print(a.count()) # 3
print(b.count()) # 7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.