have the following code to compare the time of bubblesort and quicksort:
def makeArray(groesseArray, stellenZahlen):
array = groesseArray * [None]
for i in range(0,groesseArray):
array[i] = randint(0,10**stellenZahlen)
return array
makes array
def bubble(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
#print(arr)
bubblesort algorithm
def quick(arr):
n = len(arr)
high = []
low = []
if n <= 1:
return arr
else:
pivot = arr.pop()
for i in arr:
if i > pivot:
high.append(i)
else:
low.append(i)
return quick(low) + [pivot] + quick(high)
quicksort algorithm
def timer(func(arr)):
start = time.time()
func(arr)
end = time.time()
print(end - start)
timer function to measure the time of algorithms
testArray = makeArray(500, 5)
timer(quicksort.quick(testArray))
timer(bubblesort.bubble(testArray))
which is throwing
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\Algo\compare.py", line 30, in <module>
timer(quicksort.quick(testArray))
File "C:\Users\user\PycharmProjects\Algo\compare.py", line 14, in timer
func(arr)
TypeError: 'list' object is not callable
How do I pass a function with a list into the timer function? I tried *args,**kwargs hoping it would be the solutions, but got thrown the same mistake
Thanks in advance
Change your timer function to
def timer(func, arr):
start = time.time()
func(arr)
end = time.time()
print(end - start)
and call it as follows:
timer(quicksort.quick, testArray)
timer(bubblesort.bubble, testArray)
In your code, you evaluate the sorting function the moment you call timer
. The result is a list (returned from the sorting function), which is then passed to timer
. Hence the error: you're trying to use that list as a function inside timer
.
In the above code, the function and data are passed as two separate arguments. Functions are first-class objects in Python, and can passed to other functions just as any variable can.