Python Programming Exercises,
Gently Explained
50
Solution Design
The solution uses a dictionary to track how often each number appears in the list. The keys of the
dictionary will be the number, and the values will be a count of how often the number appears in the
list.
Start with an empty dictionary and set up two variables to keep track of the most frequent
number and how many times this number has appeared in the list. Use a for loop to loop over
numbers in the numbers list. If the current number we are looping on doesn’t appear in the
dictionary’s keys, then create a key-value pair for it with the value starting at 0.
Then increment the
count for this number in the dictionary. Finally, if this count is larger than the most frequent number’s
count, update the most frequent number variable and most frequent number’s count variable with the
current number and its count.
By the time the for loop has finished, the most frequent number variable contains the mode of
the numbers list. Calculating the mode is similar Exercise #12, ―Smallest & Biggest‖. Both solutions
loop over the list
of numbers, using another variable to (in Exercise #12) keep track of the
smallest/biggest number found so far or (in this exercise) keep track of the most frequently occurring
number found so far.
Dostları ilə paylaş: