I want to write a decorator that will count the number of swaps in a sorting algorithm. I created a swap function to swap numbers and a decorator that counts each call to this function. The issues I've encountered are as follows: when I count the number of calls for multiple algorithms, it counts the "swaps" for each of them and sums them up. Another issue is that each "swap" is printed in the console. Below, I'm including the decorator, swap and a sample algorithm.
Decorator:
def swapCounter(func):
def counter(*args, **kwargs):
counter.calls += 1
print(f"Swaps {counter.calls}")
return func(*args, **kwargs)
counter.calls = 0
return counter
Swap:
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
Sample sorting algorithm:
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
swap(arr, j, j+1)
return arr
I tried adding flags in the decorator and in the swap function. In swap, the flag would be set at the end, allowing the decorator to reset at the right moment. However, this didn’t yield any results: AttributeError: 'function' object has no attribute 'calls'
def swapCounter(func):
def counter(*args, **kwargs):
counter.calls+=1
if kwargs.get("flag")==True:
print(f"Swaps {counter.calls}")
counter.calls = 0
return func(*args, **kwargs)
return counter
def swap(arr=None, i=None, j=None, flag=None):
arr[i], arr[j] = arr[j], arr[i]
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
swap(arr, j, j+1)
swap(True)
print(f"Swaps {counter.calls}")in the decorator? If you just want the final count, you need to do that outside the function.