Finding Repeated Items in Tuple

Write a Python program to find the repeated items of a tuple. Return the repeated items as a list.

Example 1:

Input: (5, 'hello', 8.3, 'hello', 9, 'a', 'a', 6, 1, 5) 
Output: ['hello', 'a', 5]

Example 2:

Input: (7, 'world', 3.14, 'd', 'new', 10, 'end', 'world', 9, 2) 
Output: ['world']

You can iterate through the tuple and use a dictionary or a counter to keep track of the counts of each item.

from collections import Counter

def find_repeats(t):
    count = Counter(t)
    return [item for item, freq in count.items() if freq > 1]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!