Q:

Python program to record similar tuple occurrence

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Recording Similar Tuple Occurrence

We are given a list of tuples with integer values where duplicate tuples are also present. We need to create a Python program to record similar tuple occurrence i.e. count the number of times a tuple has occurred.

Input:
tupList = [(9, 5), (0, 2), (3, 3), (9, 5), (3, 3)]

Output:
[(9, 5) : 2, (0, 2) : 1, (3, 3) : 2]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by creating s dictionary that contains the occurrence count of the tuple. For this, we will iterate over the list which is a sorted form, and use a counter to count distinct occurrences. Then return the distinct value dictionary.

# Python program to record similar tuple 
# occurrence using Counter 

from collections import Counter

# Initializing and printing list to tuples
tupList = [(9, 5), (0, 2), (3, 3), (9, 5), (3, 3)]
print("The elements of list of tuples is " + str(tupList))

# Recording similar tuple occurrence
similarDict = dict(Counter(tuple(val) for val in map(sorted, tupList)))

# Printing result
print("The occurrence count of each tuple in list is " + str(similarDict))

Output:

The elements of list of tuples is [(9, 5), (0, 2), (3, 3), (9, 5), (3, 3)]
The occurrence count of each tuple in list is {(5, 9): 2, (0, 2): 1, (3, 3): 2}

Method 2:

Another approach includes the use of frozenset() method that orders the tuple. This makes sure that the counting done using the counter() method is more effective.

# Python program to record similar 
# tuple occurrence 

from collections import Counter

# Initializing and printing list to tuples
tupList = [(9, 5), (0, 2), (3, 3), (9, 5), (3, 3)]
print("The elements of list of tuples is " + str(tupList))

# Recording similar tuple occurrence
similarDict = dict(Counter(tuple(frozenset(tup)) for tup in tupList))

# Printing result
print("The occurrence count of each tuple in list is " + str(similarDict))

Output:

The elements of list of tuples is [(9, 5), (0, 2), (3, 3), (9, 5), (3, 3)]
The occurrence count of each tuple in list is {(9, 5): 2, (0, 2): 1, (3,): 2}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python Regex | program to Remove leading zeros fro... >>
<< Python program to find the maximum difference betw...