Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
2 of 3 make change explicit

Thanks to Toby now the program takes:

--- 7.169409990310669 seconds to finish the program--- instead of --- 186.7168517112732 seconds--- for 100 milion numbers.

One other improvement I made was to add an extra optimization on the random generating algorithm, using numpy. So numpy.sort() was used to sort the numpy array, because it is faster for numpy arrays.


import time
import numpy

start_time0 = time.time()

def median(values):
    sortedlist =  numpy.sort(values)
    length = len(sortedlist)
    half = length // 2

    if length % 2 == 0:
        return (sortedlist[half] + sortedlist[half - 1]) // 2
        return sortedlist[half]

def main():

    m, n = 1000, 100000000
    # Random Number Generator
    start_time = time.time()
    data = numpy.random.randint(1, m, n)
    print("--- %s seconds to numpy random---" % (time.time() - start_time))
    # Median
    start_time = time.time()
    result = median(data)
    print("Result: ", result)
    print("--- %s seconds to find the Median---" % (time.time() - start_time))

if __name__ == "__main__":

    print("--- %s seconds to finish the program---" % (time.time() - start_time0))