I'm given an assignment to define a function def count_occurrences(lst, num):
where I need to find the number of times of occurrences of a number num
within a list lst
. The difficult part is that lists can be nested in lists, and I need to keep digging to the lowest level of each list to count the occurrences. For example, count_occurrences([1, [2, 1], 1, [3, [1, 3]], [4, [1], 5], [1], 1, [[1]]], 1)
returns 8.
Here is my current function:
def count_occurrences(lst, num):
if type(lst[0]) != list:
if lst[0] == num:
return 1
else:
return 0
else:
count_occurrences(lst[0], num) + count_occurrences(lst[1:], num)
But I realised that this function does not quite work. One reason is that in some cases, lists only have one element, so the index will go beyond range. In addition, in the above example to count occurrences of 1 returns 1 only, not 8.
Can anyone provide any advice in this case? Any help is much appreciated!