所以我开发了快速选择功能的代码,但它似乎没有打印出中位数。 我有一个文件名的主函数提示,然后导入该txt文件,将其拆分为数字列表,这是txt文件:
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))
答案 0 :(得分:1)
time()
方法将自纪元以来经过的秒数作为浮点数返回。要从特定开始时间打印出以秒为单位的已用时间,您需要设置start_time = time.time()
。然后你可以取time.time() - start_time
之差来获得经过的时间(以秒为单位)。
至于为什么你的函数没有输出中位数,我首先要确保你传递quickSelect
一个整数列表。现在,您似乎传递了一个字符串列表,因此您在quickSelect
中的比较是在字符串对之间而不是整数之间。尝试使用
L.append( int(locations) )