Hi, in this article lets learn about python program to find the repeated items of a tuple. Given a tuple thay contains sequence of items i.e, numbers / strings or any types. Your task is to find the items that are repeated more than once in your tuple.
There are three ways to solve this program
1) Using list
Traverse a tuple starting to end check if item is not in list, if not add item if item occurs more than once.
2) Using set
Convert the tuple to set containing unique items and check if item has occurred in tuple more than once. If yes consider it as item that has occurred more than once and print it.
3) Using Dictionary
Frame a dictionary containing key and value pair, where key is tuple item and value is number of times the key / tuple item has occurred in the tuple. Traverse the dictionary key-value pair and print the keys that has values more than one.
write a python program to find the repeated items of a tuple using list
Take the tuple of numbers and an empty list. Traverse all the items of tuple until end. tuple check if the count is greater than 1 then again check if item is already in list or not. If not in the list add it to the list.
Finally print the items of the list.
my_tuple = (1, 2, 3, 3, 4, 5, 1, 2, 5)
my_list = []
for item in my_tuple:
if my_tuple.count(item) > 1:
if item not in my_list:
my_list.append(item)
print("The Repeated Items of Tuple are ...")
print(my_list)
OUTPUT !:
The Repeated Items of Tuple are ...
[1, 2, 3, 5]
write a python program to find the repeated items of a tuple using set
OUTPUT :
Repeated items of tuple are ...
1
2
write a python program to find the repeated items of a tuple using dictionary
Lets try another technique to solve this problem, take the tuple and an empty dictionary, traverse all the items of tuple and try to from dictionary key value pair. Where key is tuple item and value is frequency of occurrence of that item. Once dictionary is framed print the keys that have values greater than 1
freq = {}
for item in my_tuple:
if item in freq:
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
if value > 1:
print(key)
OUTPUT :
# python main.py
1
2
Conclusion: If you have any queries related to the program comment down below.
0 Comments