I am right now a Python newcomer, and I study this by finishing courses on http://www.codecademy.com. This website offers an online judge system just like an ACM to exam if my code works fine. And it works great on my others code except this one.
I tried to copy this code to my local pc with Python 2.6 installed and it works.
By the way, can you suggest some Python grammar books to a beginner like me, I just want to know a little inner detail about this language...
Because I cannot post a picture here I just paste the code below:
on my mac: :
[~ tk$]cat test8.py
def median(li):
if len(li) >= 2:
li_test = sorted(li)
if len(li_test)%2 == 0:
cd1 = len(li_test)/2-1
cd2 = cd1
re = (li_test[cd1] + li_test[cd2])/2.0
else:
cd = (len(li_test)+1)/2-1
re = li_test[cd]
else:
re = li
return re
print median([1,2,3])
[~ tk$]python test8.py
2
[~ tk$]
on the websites: the title is : Practice makes perfect 15/15:
def median(li):
if len(li) >= 2:
li_test = sorted(li)
if len(li_test)%2 == 0:
cd1 = len(li_test)/2-1
cd2 = cd1
re = (li_test[cd1] + li_test[cd2])/2.0
else:
cd = (len(li_test)+1)/2-1
re = li_test[cd]
else:
re = li
return re
Oops, try again. Your function crashed on [1] as input because your function throws a "float() argument must be a string or a number" error.