Skip to content

Commit 8fdb925

Browse files
committed
Add new file
1 parent 8faa325 commit 8fdb925

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

median.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#Find the median number from a given sequence.
2+
#The sequence could be in any order and hence it is sorted first
3+
#If the sequence contains an even number of elements, the median
4+
#will be the average of the middle two elements.
5+
6+
def median(x):
7+
x = sorted(x) #Sort the list into ascending order
8+
num = x[len(x)/2] #This gets us the first of our middle numbers.
9+
num2 = x[len(x)/2 - 1] #We subtract one to get the second middle number.
10+
11+
if len(x) % 2 == 0:
12+
return (float(num) + num2)/2 #Use float so that the result will be in floating point
13+
else:
14+
return x[len(x)/2]
15+
16+
print median([1,2,3,4])
17+
print median([1,2,3,4,5])
18+
19+
# Key learning:
20+
# In the case of decimal point result
21+
# Python will divide and give us a round number
22+
# and store the remainder in memory unless
23+
# the numerator is a floating point number

0 commit comments

Comments
 (0)