Open In App

Python – Elements Frequency in Mixed Nested Tuple

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (5, (6, (7, 8, 6))) 
Output : {5: 1, 6: 2, 7: 1, 8: 1} 
Input : test_tuple = (5, 6, 7, 8)
 Output : {5: 1, 6: 1, 7: 1, 8: 1}

Method #1: Using recursion + loop

The solution to this problem involved two steps. At first, we perform flattening of tuples using recursion and then the counting is performed in a brute force manner using loop. 

Python3




# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
# using recursion + loop
 
# Helper function
def flatten(test_tuple):
 
    for tup in test_tuple:
        if isinstance(tup, tuple):
            yield from flatten(tup)
        else:
            yield tup
 
# Initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
 
# Empty tuple
res = {}
 
# Iterating over list
for ele in flatten(test_tuple):
    if ele not in res:
        res[ele] = 0
    res[ele] += 1
 
# Printing result
print("The elements frequency : " + str(res))


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Method #2: Using Counter() + recursion

This is yet another way in which this problem can be solved. In this, we employ Counter() to perform the task of counting elements. 

Python3




# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
# using recursion + Counter()
from collections import Counter
 
# Helper function
def flatten(test_tuple):
   
    for tup in test_tuple:
        if isinstance(tup, tuple):
            yield from flatten(tup)
        else:
            yield tup
 
# Initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Elements Frequency in Mixed Nested Tuple
# using recursion + Counter()
res = dict(Counter(flatten(test_tuple)))
 
# Printing result
print("The elements frequency : " + str(res))


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Method #3 : Using type(),extend(),list(),set() and count() functions

Python3




# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
 
# Initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Elements Frequency in Mixed Nested Tuple
x=[]
for i in test_tuple:
    if(type(i) is tuple):
        x.extend(list(i))
    else:
        x.append(i)
res=dict()
a=list(set(x))
for i in a:
    res[i]=x.count(i)
     
# Printing result
print("The elements frequency : " + str(res))


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Method #4 : Using type(),extend(),list(),set() and operator.countOf() methods

Python3




# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
import operator as op
# Initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Elements Frequency in Mixed Nested Tuple
x=[]
for i in test_tuple:
    if(type(i) is tuple):
        x.extend(list(i))
    else:
        x.append(i)
res=dict()
a=list(set(x))
for i in a:
    res[i]=op.countOf(x,i)
     
# Printing result
print("The elements frequency : " + str(res))


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Time Complexity: O(N*N)
Auxiliary Space: O(N)

Method #5: Using recursion and defaultdict

This code defines a function count_elements(t) that takes a tuple t as input and returns a dictionary with the frequency of each element in the tuple. The function uses a defaultdict from the collections module to create the dictionary with a default value of zero for any new key.

The function iterates over each element in the input tuple t. If the element is an integer, it increments the count of that integer in the dictionary. If the element is a tuple, it recursively calls the count_elements function on that tuple and adds the resulting frequencies to the main dictionary.

Python3




from collections import defaultdict
 
def count_elements(t):
    freq = defaultdict(int)
    for item in t:
        if isinstance(item, int):
            freq[item] += 1
        elif isinstance(item, tuple):
            sub_freq = count_elements(item)
            for k, v in sub_freq.items():
                freq[k] += v
    return freq
 
# Example usage
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
# Printing original tuple
print("The original tuple : " + str(test_tuple))
result = count_elements(test_tuple)
print("The elements frequency : " + str(result))
#This code is contributed by Vinay Pinjala.


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : defaultdict(<class 'int'>, {5: 2, 6: 2, 7: 1, 8: 1, 9: 2})

Time complexity: O(n)
The for loop iterates over each element in the input tuple once. In the worst case, the tuple can contain nested tuples, so the loop may need to iterate over the entire nested structure. The defaultdict and dict operations are O(1) time complexity. The is instance check and the recursive call to count_elements are O(1) time complexity in the average case, but in the worst case when the tuple is deeply nested, the time complexity could approach O(n), where n is the total number of elements in the tuple. Therefore, the overall time complexity of this function is O(n), where n is the total number of elements in the tuple.

Auxiliary Space:O(n)
The freq dictionary stores the frequencies of each element in the tuple. In the worst case, if all elements in the tuple are unique, the dictionary will have n entries, where n is the number of elements in the tuple.
The recursive calls to count_elements create new dictionaries for each nested tuple in the worst case. Therefore, the overall space complexity of this function is O(n), where n is the total number of elements in the tuple.

Method#6: Using nested loop

Algorithm: Counting the frequency of elements

  1. Initialize an empty dictionary freq to store the frequency of elements.
  2. Loop through each item in the input tuple t.
  3. If the item is an integer, check if it already exists in the dictionary. If not, add it to the dictionary with a value of 0.
  4. Increment the value of the item in the dictionary by 1.
  5. If the item is a tuple, loop through each subitem in the tuple. If the subitem is an integer, check if it already exists in the dictionary. If not, add it to the dictionary with a value of 0. Increment the value of the subitem in the dictionary by 1.
  6. Return the dictionary freq with the frequency of elements.

Python3




def count_elements(t):
 
    # Empty dictionary
    freq = {}
 
    for item in t:
       
        if isinstance(item, int):
            if item not in freq:
                freq[item] = 0
            freq[item] += 1
        elif isinstance(item, tuple):
            for subitem in item:
                if isinstance(subitem, int):
                    if subitem not in freq:
                        freq[subitem] = 0
                    freq[subitem] += 1
    return freq
 
 
# Initializing list
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
result = count_elements(test_tuple)
 
# Printing answer
print("The elements frequency : " + str(result))
 
# This code is contributed by tvsk


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Time complexity: O(N * M), where n is the number of items in the input tuple t, and m is the maximum number of integers in any tuple within t. This is because we need to loop through each item in t and each subitem in any tuple in t that contains integers. 

Auxiliary space: O(K), where k is the number of unique integers in t, because we store each unique integer as a key in the freq dictionary. However, this could be higher if there are many tuples with many unique integers.

Method #7: Using replace(),list(),map(),set(),split(),count() functions

Note: Here we will be converting the tuple to string

Python3




# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
 
# Initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
 
# Printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Elements Frequency in Mixed Nested Tuple
x = str(test_tuple)
 
x = x.replace("(", "")
x = x.replace(")", "")
x = x.replace(",", "")
 
y = x.split()
 
y = list(map(int, y))
z = list(set(y))
res = dict()
 
for i in z:
    res[i] = y.count(i)
 
# Printing result
print("The elements frequency : " + str(res))


Output

The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

Time Complexity : O(N) N – length of z
Auxiliary Space : O(N) N – length of res



Similar Reads

Python - Extract Even elements in Nested Mixed Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to get all the even elements from the tuple. The tuples can be nested or mixed. This kind of problem can occur in data domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (5, (7, 6, (2, (4, )))) Output : ((6, (2, (4, ))), )
4 min read
Python - Type conversion in Nested and Mixed List
While working with Python lists, due to its heterogeneous nature, we can have a problem in which we need to convert the data type of each nested element of list to a particular type. In mixed list, this becomes complex. Let's discuss the certain ways in which this task can be performed. Input : test_list = [('7', ['8', ('5', )])] Output : [(7, [8,
7 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read
Python | How to get unique elements in nested tuple
Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let's discuss certain ways in which this problem can be solved. Method #1: Using nested loop + set() The above 2 functionalities
7 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Elements frequency in Tuple Matrix
Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]] Outp
5 min read
Python - Elements frequency in Tuple
Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using defaultdict() In this, we perform task of getting all
7 min read
Python - Extract String elements from Mixed Matrix
Given a Matrix, Extract all the elements that are of string data type. Input : test_list = [[5, 6, 3], ["Gfg", 3], [9, "best", 4]] Output : ['Gfg', 'best'] Explanation : All strings are extracted.Input : test_list = [["Gfg", 3], [9, "best", 4]] Output : ['Gfg', 'best'] Explanation : All strings are extracted. Method #1 : Using list comprehension +
6 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Practice Tags :