1

So I have developed the code for a quick select function but it doesn't seem to be printing out the median. I have the main function prompt for a file name and then import that txt file, split it up into a list of numerals this is the txt file:

Offices 70
MedicalOffice  120
PostOffice 170
Mall 200

It gets imported into a list:

L = ['70', '120', '170', '200']

when it runs through the quickselect function it prints out the elapsed time being an odd number that changes every time something like 1.9083486328125e-06... first off what value of time is this in milliseconds? and when the function runs and returns the pivot it spits out this:

>>> main()
Enter a filename: Input.txt
['70', '120', '170', '200']
Time:  1.9073486328125e-06
200

Can someone tell me why it isn't working? this is the code:

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))   
4

1 回答 1

1

time()方法将自纪元以来经过的秒数作为浮点数返回。为了从特定的开始时间打印出经过的时间(以秒为单位),您需要设置您的start_time = time.time(). 然后你可以用 的差time.time() - start_time来获得以秒为单位的经过时间。

至于为什么您的函数不输出中位数,我首先要确保您传递quickSelect的是整数列表。现在,您似乎正在传递一个字符串列表,因此您的比较quickSelect是在字符串对而不是整数之间进行。尝试使用

L.append( int(locations) )
于 2013-10-08T21:18:22.753 回答