Computer Science
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)
Python Dictionaries
10 Likes
Answer
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.
Answered By
2 Likes
Related Questions
Predict the output:
d = dict() d['left'] = '<' d['right'] = '>' print('{left} and {right} or {right} and {left}')Predict the output:
d = dict() d['left'] = '<' d['right'] = '>' d['end'] = ' ' print(d['left'] and d['right'] or d['right'] and d['left']) print(d['left'] and d['right'] or d['right'] and d['left'] and d['end']) print((d['left'] and d['right'] or d['right'] and d['left']) and d['end']) print("end")Predict the output:
list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1] counts = {} ct = 0 lst = [] for num in list1: if num not in lst: lst.append(num) counts[num] = 0 ct = ct+1 counts[num] = counts[num]+1 print(counts) for key in counts.keys(): counts[key] = key * counts[key] print(counts)Create a dictionary 'ODD' of odd numbers between 1 and 10, where the key is the decimal number and the value is the corresponding number in words.
Perform the following operations on this dictionary :- Display the keys
- Display the values
- Display the items
- Find the length of the dictionary
- Check if 7 is present or not
- Check if 2 is present or not
- Retrieve the value corresponding to the key 9
- Delete the item from the dictionary corresponding to the key 9