Question
- Write a program to iterate a given list and count the occurrence of each element and create aΒ to show the count of each element.
- Given:
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
- Expected Output:
Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
My solution
- initiate an empty dictionary
- initiate an counter
- iterate over the sample_list
- 3.1 for each number, count the occurrence of that number in sample
- 3.2 use setdefault() method to add the number as key and occurrence as value to dictionary
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
count_dictionary = dict()
occurrence = 0
for number in sample_list:
occurrence = sample_list.count(number)
count_dictionary.setdefault(number, occurrence)
print(f"Printing count of each item {count_dictionary}")
Other Solution
- initiate an empty dictionary
- iterate over the sample_list
- 2.1 check if the number appear in the dictionary
- 2.1.1 if the number does not appear in the dictionary, add the number as key and 1 as value to the dictionary
- 2.1.2 if the appear in the dictionary, increase the value by 1.
- 2.1 check if the number appear in the dictionary
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)
count_dict = dict()
for item in sample_list:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)
Credit
exercise on Pynative
Top comments (0)