To solve this problem, we need to traverse the nested list and count the occurrences of a specified element at each level of nesting. Here's how you can do it step by step:
-
Initialization: Start by initializing a list to store the frequency counts at each level of nesting.
-
Recursive Traversal: Use a recursive function to traverse the nested list. The recursion allows us to dive into deeper levels of the list while keeping track of the current nesting level.
-
Counting Elements: For each element at the current level, check if it's the target element. If it is, increment the count for the current nesting level.
-
Handling Nested Lists: If an element is a list itself, recursively call the function to process that sublist, increasing the nesting level by 1.
-
Result Compilation: After traversing the entire list, compile the counts into the desired format.
Here’s the implementation of the solution:
def freq_count(lst, el):
def helper(sublist, level, freq_map):
# Ensure the frequency map has a place for the current level
if level >= len(freq_map):
freq_map.append(0)
for item in sublist:
if isinstance(item, list):
helper(item, level + 1, freq_map)
elif item == el:
freq_map[level] += 1
# Frequency map to store counts at each level
freq_map = []
helper(lst, 0, freq_map)
# Convert the frequency map to the required format
return [[i, freq_map[i]] for i in range(len(freq_map))]
# Test cases
print(freq_count([1, 4, 4, [1, 1, [1, 2, 1, 1]]], 1)) # ➞ [[0, 1], [1, 2], [2, 3]]
print(freq_count([1, 5, 5, [5, [1, 2, 1, 1], 5, 5], 5, [5]], 5)) # ➞ [[0, 3], [1, 4], [2, 0]]
print(freq_count([1, [2], 1, [[2]], 1, [[[2]]], 1, [[[[2]]]]], 2)) # ➞ [[0, 0], [1, 1], [2, 1], [3, 1], [4, 1]]
Explanation:
-
helper(sublist, level, freq_map):
sublist: The current list or sublist being processed.
level: The current level of nesting.
freq_map: A list where the index represents the nesting level, and the value at that index represents the frequency of the target element at that level.
-
if isinstance(item, list):: This checks if the current item is a list. If it is, the function calls itself recursively to process the sublist.
-
elif item == el:: If the item matches the target element el, the function increments the count for the current level.
-
freq_map.append(0): This ensures that the frequency map list has a slot for the current level.
-
return [[i, freq_map[i]] for i in range(len(freq_map))]: This converts the frequency map into the desired list of lists format.
Output:
- The function returns a list where each sublist contains a level and the count of the target element at that level.
This implementation is efficient and handles lists of arbitrary depth, correctly counting the occurrences of the target element at each nesting level.