Python - Maximum frequency in Tuple
Last Updated :
16 May, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in the tuple. Tuple, being quite a popular container, this type of problem is common across the web development domain. Let's discuss certain ways in which this task can be performed.
Input : test_tuple = (6, 7, 10, 11, 10)
Output : 10
Input : test_tuple = (5, 5, 5)
Output : 5
Method #1: Using count() + loop
The combination of the above functions can be used to solve this problem. This is a brute-force approach to solve this problem. In this, we use count() to perform the counting of elements.
Python3
# Python3 code to demonstrate working of
# Maximum frequency in Tuple
# Using loop + count()
# Initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# Printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using loop + count()
cnt = 0
res = test_tuple[0]
for ele in test_tuple:
curr_freq = test_tuple.count(ele)
if(curr_freq > cnt):
cnt = curr_freq
res = ele
# Printing result
print("Maximum element frequency tuple : " + str(res))
Output : The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6
Method #2: Using max() + Counter() + lambda
The combination of the above functions can be used to solve this problem. In this, we use Counter() to find the frequency of all elements and max() is used to find the maximum of it.
Python3
# Python3 code to demonstrate working of
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
from collections import Counter
# Initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# Printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
res = max(Counter(test_tuple).items(), key=lambda ele: ele[1])
# Printing result
print("Maximum element frequency tuple : " + str(res[0]))
Output : The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6
Method #3: Using the statistics mode() function
This approach defines a function max_frequency_in_tuple() which uses statistics.mode() function to find the element with the highest frequency in a given tuple. It then returns the element with the highest frequency. The print() statements at the bottom of the code test the function with two sample inputs and print the outputs.
Step-by-step approach:
- Use the statistics mode() function to find the element with the highest frequency in the tuple.
- Return the element with the highest frequency.
Python3
import statistics
def max_frequency_in_tuple(test_tuple):
# Use the statistics mode() function to find the element
# with the highest frequency in the tuple
max_freq_element = statistics.mode(test_tuple)
# Return the element with the highest frequency
return max_freq_element
# Testing the function with given inputs
print(max_frequency_in_tuple((6, 7, 10, 11, 10)))
print(max_frequency_in_tuple((5, 5, 5)))
Time complexity: O(nlogn), where n is the length of the array
Auxiliary Space: O(1)
Method 4: Using a dictionary
Step-by-step approach:
- Initialize an empty dictionary freq_dict to store the frequency of each element.
- Iterate through the elements of the tuple using a for loop.
- For each element, use the get() method of the dictionary to retrieve its current frequency. If the element is not yet in the dictionary, the get() method returns a default value of 0. Increment the retrieved frequency by 1 and store the new frequency in the dictionary.
- Use the max() function to find the element with the maximum frequency. The key argument of max() specifies a function to extract a comparison key from each dictionary key. In this case, we use freq_dict.get as the key function, which returns the frequency of each element in the dictionary.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Maximum frequency in Tuple
# Using dictionary
# Initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# Printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using dictionary
freq_dict = {}
for ele in test_tuple:
freq_dict[ele] = freq_dict.get(ele, 0) + 1
res = max(freq_dict, key=freq_dict.get)
# Printing result
print("Maximum element frequency tuple : " + str(res))
OutputThe original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6
Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(n), where n is the length of the tuple.
Method 5: Using numpy
- Import the numpy module
- Convert the tuple to a numpy array using the np.array() function
- Use the np.unique() function to get the unique elements and their frequency counts in the array
- Find the index of the maximum frequency count using the np.argmax() function
- Get the corresponding unique element using the np.unique() function with the return_counts argument set to True
- Print the element with the maximum frequency count
Python3
# Python code to demonstrate working of
# Maximum frequency in Tuple
# Using numpy
# Import numpy module
import numpy as np
# Initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
# Printing original tuple
print("The original tuple : " + str(test_tuple))
# Maximum frequency in Tuple
# Using numpy
unique_elements, element_counts = np.unique(np.array(test_tuple), return_counts=True)
max_freq_idx = np.argmax(element_counts)
res = unique_elements[max_freq_idx]
# Printing result
print("Maximum element frequency tuple : " + str(res))
Output:
The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6
Time complexity: O(n*log(n)), where n is the length of the input tuple.
Auxiliary space: O(n), where n is the length of the input tuple.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read