所以我開發了一個快速選擇函數的代碼,但它似乎沒有打印出中位數。 我有一個文件名的主要功能提示,然後導入txt文件,把它分解成數字的列表,這是txt文件:Python-Quickselect函數查找中位數
Offices 70
MedicalOffice 120
PostOffice 170
Mall 200
它被導入到一個列表:
L = ['70', '120', '170', '200']
當它通過quickselect函數運行時,它會打印出經過的時間是每次類似1.9083486328125e-06之類的變化的奇數...首先關閉什麼值的時間是以毫秒爲單位的?當功能運行並返回它的樞軸吐出來:
>>> main()
Enter a filename: Input.txt
['70', '120', '170', '200']
Time: 1.9073486328125e-06
200
有人可以告訴我爲什麼它不工作?這是代碼:
import time
start_time = 0
def quickSelect(L, k):
start_time = time.time()
if len(L) != 0:
pivot = L[(len(L)//2)]
smallerList = []
for i in L:
if i<pivot:
smallerList.append(i)
largerList=[]
for i in L:
if i>pivot:
largerList.append(i)
m=len(smallerList)
count=len(L)-len(smallerList)-len(largerList)
if k >= m and k < m + count:
end_time = time.time()
print("Time: ", end_time - start_time)
return pivot
elif m > k:
return quickSelect(smallerList, k)
else:
return quickSelect(largerList, k - m - count)
def main():
dataFilename = input('Enter a filename: ')
dataFile = open(dataFilename)
L = []
for inputLine in dataFile:
splittext = inputLine.split()
place = splittext[0]
locations = splittext[1]
L += [locations]
print(L)
print(quickSelect(L, len(L)//2))
看看結果'排序(L)'如果你想找出爲什麼''200''是中值:-) – WolframH