I just had a problem with Python which I eventually fixed myself. Although I'm still wondering what's the difference of using
arrayName
and
arrayName[:]
even if they have the same values. Here's my code where I had the problem:
def quickSort(ar, start, end):
count = 0
if end - start >= 2:
p = ar[end-1]
pos = start
for i in range(start, end-1):
if ar[i] < p:
if i != pos:
ar[i], ar[pos] = ar[pos], ar[i]
pos += 1
count += 1
ar[pos], ar[end-1] = ar[end-1], ar[pos]
count += 1
count += quickSort(ar, start, pos)
count += quickSort(ar, pos+1, end)
return count
def insertion_sort(ar):
shift = 0
for i in range(1, len(ar)):
j = i-1
key = ar[i]
while (j > -1) and (ar[j] > key):
ar[j+1] = ar[j]
shift += 1
j -= 1
ar[j+1] = key
return shift
n = int(input())
ar = list(map(int, input().split()))
print(insertion_sort(ar) - quickSort(ar, 0, n))
The above will print -18
but if I change the last line into
print(insertion_sort(ar[:]) - quickSort(ar[:], 0, n))
it will print 1
which is the correct (the return value of insertion_sort() is 9 and the return value of quickSort() is 8). Why is it returning a wrong value when I didn't use list slicing?