11
Question Question 9(c)
Predict the output:
text = "abracadabraaabbccrr"
counts = {}
ct = 0
lst = []
for word in text:
if word not in lst:
lst.append(word)
counts[word] = 0
ct = ct + 1
counts[word] = counts[word] + 1
print(counts)
print(lst) Output
{'a': 7, 'b': 4, 'r': 4, 'c': 3, 'd': 1}
['a', 'b', 'r', 'c', 'd']
Explanation
This python program counts the frequency of each character in a string. Here is a step-by-step explanation of the program:
- Initialize the variables
- The
textvariable stores the input string "abracadabraaabbccrr". - The
countsvariable is a dictionary that stores the frequency of each character in the string. - The
ctvariable is a counter that keeps track of the total number of characters in the string. - The
lstvariable is a list that stores the unique characters in the string.
- The
- Loop through each character
wordin thetextstring- If the character has not been seen before, it is added to the
lstlist and a new key is added to thecountsdictionary with a value of 0. - The
ctvariable is incremented by 1. - The value of the character's key in the
countsdictionary is incremented by 1. This value keeps a count of the number of times this character has appeared in the string so far.
- If the character has not been seen before, it is added to the
- Finally, the
countsdictionary and thelstlist are printed to the console. Thecountsdictionary displays the frequency of each character in the string, and thelstlist displays the unique characters in the string.