我有一个列表。一旦我创建它,print list
的结果是:
[1, 3, 5, 60, 72, 83, 120, 180]
然后将作为参数传递给函数。在该函数的第一行(没有对列表进行任何更改),它被传递给另一个函数。在这里打印列表的结果如下:
[1, 3, 5, 60, 72, 83, 120, 180]
[]
同样,这是在完成任何其他操作之前。第二个函数是:
def median(li):
print li
lenli = len(li)
if lenli%2==0:
i = (((lenli/2) + (lenli/2 + 1)) / 2)
print i
return li[i]
else:
return l[lenli/2 - 1]
一旦程序到达return li[i]
,它抛出这个错误:IndexError: list index out of range
你知道我做错了什么吗?我已经尝试访问列表(0,1)的其他元素,但仍然抛出相同的错误。
编辑:第一个函数是:
def binarysearch(target, tosearch):
print tosearch
i = median(tosearch)
while(i != target):
if i < target:
del tosearch[i:len(tosearch)]
else:
del tosearch[0:i]
i = median(tosearch)
return True
EDIT2一个示例输入是这个数字列表,[1, 3, 5, 60, 72, 83, 120, 180]
作为源列表,5
作为目标列表。第一次调用median()
应该返回72
,然后返回binarysearch()
中调用的每个缩短列表的中位数。最终binarysearch()
应该返回True。
我看过你的代码了。并做了一些小修改:
def median(li):
if not len(li)%2:
i = (((len(li)/2) + (len(li)/2 + 1)) / 2)
return i, li[i]
else:
return i, li[len(li)/2 - 1]
def binarysearch(target, tosearch):
while True:
idx, med = median(tosearch)
if med == target:
return True
elif med < target:
tosearch = tosearch[idx:]
elif med > target:
tosearch = tosearch[:idx]
l = [1, 3, 5, 60, 72, 83, 120, 180]
print binarysearch(5, l)
结果:
>>>
True
我不打算修复代码的每一个方面,但这应该会让你朝着正确的方向前进。好运。