Python - Elements Frequency in Mixed Nested Tuple

Python - Elements Frequency in Mixed Nested Tuple

Let's tackle how to determine the frequency of elements in a mixed nested tuple.

Objective: Given a nested tuple containing both single elements and other tuples, find the frequency of each element.

Example: Consider the tuple:

data = (1, (2, 3), 4, (2, (3, 4)), 5) 

Determine the occurrences of each number.

1. Using a Recursive Approach:

A nested tuple means we'll encounter tuples inside tuples. To deal with this, a recursive function works best.

def count_elements_in_tuple(t, element_counts={}): for item in t: if isinstance(item, tuple): count_elements_in_tuple(item, element_counts) else: element_counts[item] = element_counts.get(item, 0) + 1 return element_counts data = (1, (2, 3), 4, (2, (3, 4)), 5) element_counts = count_elements_in_tuple(data) for element, count in element_counts.items(): print(f"Element: {element}, Occurrences: {count}") 

2. Using a Stack:

This is a non-recursive approach using a stack. It's an iterative solution where we push and pop elements from the stack to process them.

def count_elements_in_tuple(t): element_counts = {} stack = [t] while stack: current = stack.pop() if isinstance(current, tuple): stack.extend(current) else: element_counts[current] = element_counts.get(current, 0) + 1 return element_counts data = (1, (2, 3), 4, (2, (3, 4)), 5) element_counts = count_elements_in_tuple(data) for element, count in element_counts.items(): print(f"Element: {element}, Occurrences: {count}") 

Both methods will give the following Output:

Element: 1, Occurrences: 1 Element: 2, Occurrences: 2 Element: 3, Occurrences: 2 Element: 4, Occurrences: 2 Element: 5, Occurrences: 1 

Explanation: Both the recursive and the stack approach check if an item in the tuple is itself a tuple. If it is, they will process its contents further. Otherwise, they'll simply count the occurrence of the element.


More Tags

discord-jda exceljs virtualenv group-policy ibaction cookie-httponly post-build customization firebase-cli identity

More Programming Guides

Other Guides

More Programming Examples