This is a Python puzzle from Codecademy. It involves writing a function to find the median in a list of numbers. Here’s the code:
array = []
x = raw_input(“Enter a number.”)
while x != “”:
array.append(x)
x = raw_input(“Anything else?”)
def median(list):
list2 = sorted(list)
length = len(list)
length2 = length/2
median = 0
if length == 1:
median = list[0]
elif length % 2 != 0:
for i in range(length):
if len(list2[0:i]) == len(list2[i+1:]):
median = list2[i]
elif length % 2 == 0:
sub_list1 = list2[0:length2]
sub_list2 = list2[length2:]
a = float(sub_list1[len(sub_list1)-1])
b = float(sub_list2[0])
median = (a + b) / 2
return median
print “The median of your list is”, median(array)
First thing to do is sort the list. Then, in a list with an odd number of items, the median, m, is the element in which the number elements before it is equal to the number of elements that it. For example, in a list [1,2,3,4,5], the median is 3 because there are two numbers before 3 and two numbers after 3. My program does that with the following code:
elif length % 2 != 0:
for i in range(length):
if len(list2[0:i]) == len(list2[i+1:]):
median = list2[i]
In a list with an even number of items. You simply divide the list into two halves, sub-list #1 and sub-list #2. Then the median is simply the sum of the last number in sub-list #1 and the first number in sub-list#2, divided by two. This is illustrated by the following code:
elif length % 2 == 0:
sub_list1 = list2[0:length2]
sub_list2 = list2[length2:]
a = float(sub_list1[len(sub_list1)-1])
b = float(sub_list2[0])
median = (a + b) / 2
That’s it for today as I’m fairly tired from learning new stuff like Django and SQL.