Question

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))   
Was it helpful?

Solution

The time() method returns the elapsed seconds since the epoch as a float. In order to print out the elapsed time in seconds from a particular start time, you need to set your start_time = time.time(). Then you can take the difference of time.time() - start_time to get the elapsed time in seconds.

As for why your function isn't outputting the median, I would first make sure that you are passing quickSelect a list of integers. Right now, it appears that you are passing a list of strings, so your comparisons in quickSelect are between pairs of strings instead of integers. Try using

L.append( int(locations) )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top