我的Python出现问题:float()参数必须是字符串或数字
我现在是个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$]
在网站上:标题是: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.
1 个回答
1
else:
re = li
这个错误发生的原因是,如果 li
的长度是 1 或 0,那么你就直接返回了这个列表 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
你只取了两个中间元素中的一个,然后把同样的数字加了两次再除以二。正确的做法应该是
if len(li_test) % 2 == 0:
cd1 = len(li_test) / 2
cd2 = cd1 - 1
re = (li_test[cd1] + li_test[cd2])/2.0