Write a Python program to Elements Frequency in Mixed Nested Tuple


The program defines a function "flatten" which takes a tuple "val" as input. The function uses a for loop to iterate over the elements in "val". For each element "e", if "e" is a tuple, the function uses a yield statement to yield the elements of "e" using a recursive call to "flatten". If "e" is not a tuple, the function uses a yield statement to yield "e".

Outside the function, a tuple "val" is created and its original elements are printed. Then, an empty dictionary "res" is created. The function "flatten" is called with "val" as input, and the returned elements are used to fill the dictionary "res". The key of each element is used as the dictionary key, and the value is initialized to 0. For each occurrence of an element in the returned sequence, its corresponding value in the dictionary is incremented by 1. Finally, the elements frequency is printed.

Source Code

def flatten(val):
	for e in val:
		if isinstance(e, tuple):
			yield from flatten(e)
		else:
			yield e
 
val = (10, 20, (20, 10), 30, (40, 50, 60), 60 ,70)
 
print("The Original Elements : " ,val)
 
res = {}
for i in flatten(val):
	if i not in res:
		res[i] = 0
	res[i] += 1
 
 
print("The Elements Frequency : " , res)

Output

The Original Elements :  (10, 20, (20, 10), 30, (40, 50, 60), 60, 70)
The Elements Frequency :  {10: 2, 20: 2, 30: 1, 40: 1, 50: 1, 60: 2, 70: 1}


Example Programs