P ython p rogramming e xercises


Special Cases and Gotchas



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə43/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   39   40   41   42   43   44   45   46   ...   124
PythonProgrammingExercisesGentlyExplained

Special Cases and Gotchas 
If the numbers parameter is an empty list, the function should return None. You should put the 
code that checks this at the start of the function. 
Now try to write a solution based on the information in the previous sections. If you still have 
trouble solving this exercise, read the Solution Template section for additional hints. 
Solution Template 
Try to first write a solution from scratch. But if you have difficulty, you can use the following 
partial program as a starting place. Copy the following code from https://invpy.com/mode-template.py and 
paste it into your code editor. Replace the underscores with code to make a working program: 
def mode(numbers): 
# Special case: If the numbers list is empty, return None: 
if len(numbers) == ____: 
return ____ 
# Dictionary with keys of numbers and values of how often they appear: 
numberCount = {} 
# Track the most frequent number and how often it appears: 
mostFreqNumber = None 
mostFreqNumberCount = ____ 
# Loop through all the numbers, counting how often they appear: 
for number in ____: 
# If the number hasn't appeared before, set it's count to 0. 
if ____ not in numberCount: 
numberCount[____] = ____ 
# Increment the number's count: 
numberCount[____] += ____ 
# If this is more frequent than the most frequent number, it 


Python Programming Exercises, Gently Explained 
51 
# becomes the new most frequent number: 
if numberCount[number] > ____: 
mostFreqNumber = ____ 
mostFreqNumberCount = ____[____] 
# The function returns the most frequent number: 
return mostFreqNumber 
The complete solution for this exercise is given in Appendix A and https://invpy.com/mode.py. You 
can view each step of this program as it runs under a debugger at https://invpy.com/mode-debug/


52 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   39   40   41   42   43   44   45   46   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin