我现在是Python的新人,我通过完成http://www.codecademy.com的课程来学习。这个网站提供了一个在线评判系统,就像ACM一样,检查我的代码是否正常。除了这一个,它在我的其他代码上运行得很好。
我尝试将此代码复制到安装了Python 2.6的本地电脑上,并且可以正常工作。
顺便说一句,你能为像我这样的初学者推荐一些Python语法书吗?我只想知道关于这种语言的一些内部细节......
因为我无法在此处发布图片,所以我只需粘贴以下代码:
在我的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$]
在网站上:标题是:练习完美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.
答案 0 :(得分:1)
else:
re = li
发生错误是因为如果li
的长度为1或0,那么您将返回list
li
。
>>> median([1])
[1]
>>> median([0])
[0]
也许你想要
if len(li) >= 1:
...
else:
raise IndexError("No items in this list")
代码中的另一个错误是如果列表中有偶数个元素,则应该取两个中间元素的平均值。但是在你的代码中,
if len(li_test)%2 == 0:
cd1 = len(li_test)/2-1
cd2 = cd1
re = (li_test[cd1] + li_test[cd2])/2.0
您从两个中间元素中选择一个,并将相同的数字相加两次并除以2。它应该是
if len(li_test) % 2 == 0:
cd1 = len(li_test) / 2
cd2 = cd1 - 1
re = (li_test[cd1] + li_test[cd2])/2.0