148k views
5 votes
Write a recursive function count(lst,target) that finds the number of occurrences of target in a nested list, where each item in the list is either a number, or, another list (which itself could be listed). The list transversal will be similar to the function total written in class. Example:

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

2

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

4

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

0

1 Answer

3 votes

Final answer:

The question involves writing a recursive function count(lst, target) in Python to count occurrences of a target value in a nested list. This function works by iterating through each element, recursively calling itself if an element is a sublist, or incrementing a counter if the element matches the target.

Step-by-step explanation:

The provided question asks for a recursive function count(lst, target) that counts the number of times a certain value (target) appears in a nested list (lst), which may contain both numbers and subordinate lists. Below is a sample implementation of such a function in Python:

def count(lst, target):
occurrences = 0
for element in lst:
if isinstance(element, list): # If the element is a list, make a recursive call
occurrences += count(element, target)
elif element == target: # If the element is the target, increment the occurrences
occurrences += 1
return occurrences

To find the number of occurrences of 1 in the nested list [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], you would call count([1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1) and it would return 2.

User Avck
by
7.8k points