My example below. I have tried adding global
to the variable that I want to change but doesn't help. The error I'm getting is in the comment.
def getNumOfSwapsToSort(array):
sorted = array.copy()
sorted.sort()
swaps = 0
def swap():
currentSwaps = 0
for i, el in enumerate(array):
if ((len(array) - 1) == i) and currentSwaps != 0:
swap()
elif el != sorted[i]:
idx = sorted.index(el)
temp = array[idx]
array[idx] = el
array[i] = temp
# UnboundLocalError: local variable 'swaps' referenced before assignment
# if I use global swaps, then NameError: name 'swaps' is not defined
swaps += 1
currentSwaps += 1
swap()
return swaps