Python Programming Exercises,
Gently Explained
48
and paste it into your code editor. Replace the underscores with code to make a working program:
def median(numbers):
# Special case: If the numbers list is empty, return None:
if len(numbers) == ____:
return ____
# Sort the numbers list:
____.sort()
# Get the index of the middle number:
middleIndex = len(____) // ____
# If the numbers list has an even length, return the average of the
# middle two numbers:
if len(numbers) % ____ == 0:
return (numbers[____] + numbers[middleIndex - ____]) / ____
# If the numbers list has an odd length, return the middlemost number:
else:
return numbers[____]
The complete solution for this exercise is given in Appendix A and
https://invpy.com/median.py.
You can view each step of this program as it runs under a debugger at
https://invpy.com/median-debug/.
49
E X E R C I S E # 1 6 : M O D E
mode([1, 1, 2, 3, 4])
→
1
Mode is the third statistical calculation exercise in this book. The mode is the number that
appears
most frequently in a list of numbers. Together with the median and average, you can get a descriptive
summary of a list of numbers. This exercise tests your ability to use a dictionary to keep a count of the
numbers in a list to find the most frequent number.
Dostları ilə paylaş: