Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Step Frequency of elements in List
Next article icon

Python – Elements Frequency in Mixed Nested Tuple

Last Updated : 15 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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



Next Article
Python - Step Frequency of elements in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

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,
    4 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. Inp
    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 def
    7 min read
  • Python - Step Frequency of elements in List
    Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
    4 min read
  • Python - Get Even indexed elements in Tuple
    Sometimes, while working with Python data, one can have a problem in which we need to perform the task of extracting just even indexed elements in tuples. This kind of problem is quite common and can have possible application in many domains such as day-day programming. Let's discuss certain ways in
    5 min read
  • Python - Restrict Elements Frequency in List
    Given a List, and elements frequency list, restrict frequency of elements in list from frequency list. Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1} Output : [1, 4, 5, 4, 4, 6] Explanation : Limit of 1 is 1, any occurrence more than that is removed.
    5 min read
  • Python - Similar index elements frequency
    Sometimes, while working with Python list, we can have a problem in which we need to check if one element has similar index occurrence in other list. This can have possible application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using sum() + zip() The
    7 min read
  • Sort List Elements by Frequency - Python
    Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
    3 min read
  • Python | Frequency grouping of list elements
    Sometimes, while working with lists, we can have a problem in which we need to group element along with it's frequency in form of list of tuple. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method to perform this particular task. In this
    6 min read
  • Python - List Frequency of Elements
    We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences