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]
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.
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.
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