2

I'm finally getting around to recursion in Python and trying to count the number of occurrences of a target number in a list. However, I'm running into issues with counting occurrences in a nested list of numbers.

For example

def count(lst, target):

    if lst == []:
        return 0
    if lst[0] == target:
        return 1 + count(lst[1:], target)
    else:
        return 0 + count(lst[1:], target)

Output

>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )

Output: 1

Expected output: 2

Is there an easy way to flatten nested-lists in Python? Or a simple way for me to account for the fact that there is a nested-list in my code?

23k
  • 1,596
  • 3
  • 23
  • 52
  • 1
    http://stackoverflow.com/questions/11377208/recursive-generator-for-flattening-nested-lists?rq=1 This might be of help. – Krash Feb 17 '16 at 05:09

2 Answers2

5
def count(lst, target):
    n = 0
    for i in lst:
        if i == target:
            n += 1
        elif type(i) is list:
            n += count(i, target)
    return n
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
jfsturtz
  • 397
  • 4
  • 13
4

You just need an extra case to deal with lst[0] being a sublist, like:

def count(lst, target):

    if lst == []:
        return 0
    if lst[0] == target:
        return 1 + count(lst[1:], target)
    # If first element is a list, descend into it to count within it,
    #    and continue with counts of remaining elements
    elif type(lst[0]) == list:
        return count(lst[0], target) + count(lst[1:], target)
    else:
        return 0 + count(lst[1:], target)
Marius
  • 58,213
  • 16
  • 107
  • 105