Python 如果pivot不是';中期选举
好的,我开发了一个通用的quickselect函数,它用于查找列表的中间值Python 如果pivot不是';中期选举,python,list,function,indexing,quickselect,Python,List,Function,Indexing,Quickselect,好的,我开发了一个通用的quickselect函数,它用于查找列表的中间值 k = len(aList)//2 and the list is aList = [1,2,3,4,5] 那么,如果pivot每次都在列表的第一项启动,程序的行为会有什么不同呢。我一定要去中心吗?另外,我应该从哪里开始time.clock()以查找函数的运行时间。这是密码 def quickSelect(aList, k) if len(aList)!=0: pivot=aList[(len(aList
k = len(aList)//2 and the list is aList = [1,2,3,4,5]
那么,如果pivot每次都在列表的第一项启动,程序的行为会有什么不同呢。我一定要去中心吗?另外,我应该从哪里开始time.clock()以查找函数的运行时间。这是密码
def quickSelect(aList, k)
if len(aList)!=0:
pivot=aList[(len(aList)//2)]
smallerList = []
for i in aList:
if i<pivot:
smallerList.append(i)
largerList=[]
for i in aList:
if i>pivot:
largerList.append(i)
m=len(smallerList)
count=len(aList)-len(smallerList)-len(largerList)
if k >= m and k<m + count:
return pivot
elif m > k:
return quickSelect(smallerList,k)
else:
return quickSelect(largerList, k - m - count)
def quickSelect(列表,k)
如果我是莱恩=0:
pivot=aList[(len(aList)//2)]
smallerList=[]
对于我来说:
如果ipivot:
追加(一)
m=len(小列表)
计数=列(列表)-列(小列表)-列(大列表)
如果k>=m和k:
返回quickSelect(小列表,k)
其他:
返回quickSelect(大列表,k-m-count)
我认为在开始时放置轴没有任何问题。但这只是初始化枢轴。枢轴的整个思想通常是找到中间元素
请尝试以下方法计算时间:
import time
start_time = 0
aList = [1,2,3,4,5]
k = len(aList)//2
def quickSelect(aList, k):
start_time = time.time()
# print "%10.6f"%start_time
# pivot = aList[0]
if len(aList) != 0:
pivot = aList[(len(aList) // 2)]
smallerList = []
for i in aList:
if i < pivot:
smallerList.append(i)
largerList = []
for i in aList:
if i > pivot:
largerList.append(i)
m = len(smallerList)
count = len(aList) - len(smallerList) - len(largerList)
if k >= m and k < m + count:
print "Pivot", pivot
# print "%10.6f"%time.time()
print "time: ", time.time() -start_time
return pivot
elif m > k:
return quickSelect(smallerList, k)
else:
return quickSelect(largerList, k - m - count)
quickSelect(aList, k)
Pivot 3
time: 0.0