In this python tuple program, we will calculate the frequency of elements in a tuple.
Steps to solve the program
- Take a tuple as input and create an empty dictionary.
- Use for loop to iterate over each character from the tuple.
- If a character is not in the dictionary then add that character as a key and 0 as its value.
- If the character is already in the list then add 1 to the value.
- Print the output.
tup = ('a','b','c','d','b','a','b')
print("Original tuple: ",tup)
d = {}
for char in tup:
if char not in d:
d[char] = 0
if char in d:
d[char] += 1
print("Frequency count : ",d)
Output :
Original tuple: ('a', 'b', 'c', 'd', 'b', 'a', 'b')
Frequency count : {'a': 2, 'b': 3, 'c': 1, 'd': 1}