因此,我已经开发了一个快速选择函数的代码,但它似乎没有打印出中位数。我有一个文件名的主函数提示符,然后导入那个txt文件,将它分割成一个数字列表--这是txt文件:
Offices 70
MedicalOffice 120
PostOffice 170
Mall 200它被导入到一个列表中:
L = ['70', '120', '170', '200']当它运行在quickselect函数中时,它会打印出经过的时间是一个奇数,每次像1.90834486328125e-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)) 发布于 2013-10-08 21:18:22
time()方法以浮点的形式返回自划时代以来经过的秒。为了从特定的启动时间打印出以秒为单位的时间,您需要设置您的start_time = time.time()。然后,您可以使用time.time() - start_time的差异来获得以秒为单位的运行时间。
至于为什么您的函数没有输出中间值,我首先要确保您正在向quickSelect传递一个整数列表。现在,您似乎要传递一个字符串列表,因此您在quickSelect中的比较是在字符串对之间而不是整数之间进行的。试着使用
L.append( int(locations) )https://stackoverflow.com/questions/19258457
复制相似问题