Computer Science
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)
Python Dictionaries
9 Likes
Answer
Output
{2: 3, 3: 3, 5: 2, 1: 2}
{2: 6, 3: 9, 5: 10, 1: 2}
Explanation
This python program counts the frequency of each number in a list and then multiplies each frequency by its corresponding number. Here is a step-by-step explanation of the program:
- Initialize the variables
- The
list1variable stores the input list [2, 3, 3, 2, 5, 3, 2, 5, 1, 1]. - The
countsvariable is a dictionary that stores the frequency of each number in the list. - The
ctvariable is a counter that keeps track of the total number of numbers in the list. - The
lstvariable is a list that stores the unique numbers in the list.
- The
- Loop through each number
numin thelist1- If the number 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 number's key in the
countsdictionary is incremented by 1.
- If the number has not been seen before, it is added to the
- The
countsdictionary is printed to the console after the first loop, displaying the frequency of each number in the list. - Another loop is executed through the keys in the
countsdictionary. For each key, its corresponding value is multiplied by the key and the new value is assigned back to the key in thecountsdictionary. - The final
countsdictionary is printed to the console, showing the frequency of each number multiplied by the number itself.
Answered By
3 Likes
Related Questions
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:
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)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
Find the errors:
text = "abracadbra" counts = {} for word in text : counts[word] = counts[word] + 1