Skip to content

Commit e4b1196

Browse files
committed
Fix median function
1 parent 8386b7d commit e4b1196

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

ch06-functions-and-loops/5-challenge-track-your-investments.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# Solution to challenge
33

44

5-
# Calculate compound interest to track the growth of an investment
5+
# Calculate interest to track the growth of an investment
66

77

88
def invest(amount, rate, years):

ch09-lists-tuples-and-dictionaries/4-challenge-list-of-lists.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,27 @@ def enrollment_stats(list_of_universities):
1818

1919

2020
def mean(values):
21+
"""Return the mean value in the list `values`"""
2122
return sum(values) / len(values)
2223

2324

2425
def median(values):
26+
"""Return the median value of the list `values`"""
2527
values.sort()
26-
length = len(values)
27-
if not length % 2:
28-
return values[(length - 1) / 2]
29-
return values[int(length / 2)]
28+
# If the number of valus is odd,
29+
# return the middle value of the list
30+
if len(values) % 2 == 1:
31+
# The value at the center of the list is the value
32+
# at whose index is half of the length of the list,
33+
# rounded down
34+
center_index = int(len(values) / 2)
35+
return values[center_index]
36+
# Otherwise, if the length of the list is even, return
37+
# the mean of the two center values
38+
else:
39+
left_center_index = (len(values) - 1) / 2
40+
right_center_index = (len(values) + 1) / 2
41+
return mean([left_center_index, right_center_index])
3042

3143

3244
universities = [

0 commit comments

Comments
 (0)