Kevin Dumaresq
Kevin Dumaresq

Reputation: 13

the number of items at a given depth in all sub-lists of a list

I feel like i'm going at it all wrong. I am recursing at the depth of a list as if it was a Tree. This causes problems because It's an arbitrary list that can have strings, ints ... Here's what I have

def visit_depth(list_, depth):
    if depth == 0:
        return 1
    elif depth >0:
        return sum([visit_depth(l, depth - 1) for l in list_])
    else:
        return 0

Upvotes: 1

Views: 47

Answers (1)

Amadan
Amadan

Reputation: 198556

This causes problems because It's an arbitrary list that can have strings, ints

Guard against them.

def deep_len(obj, depth=0):
    if isinstance(obj, list):
        if depth == 0:
            return len(obj)
        else:
            return sum(deep_len(elem, depth - 1) for elem in obj)
    else:
        return 0

deep_len([1,2,[2,5],[3]], 0)
# => 4      (this list itself has 4 elements)
deep_len([1,2,[2,5],[3]], 1)
# => 3      (going 1 level down there's just 3 elements)
deep_len([1,2,[2,5],[3]], 2)
# => 0      (there is no 2 levels down)

Upvotes: 5

Related Questions