【发布时间】:2015-10-10 03:58:22
【问题描述】:
我刚刚遇到了 Python 的问题,最终我自己解决了。虽然我仍然想知道使用有什么区别
arrayName
和
arrayName[:]
即使它们具有相同的值。这是我遇到问题的代码:
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))
上面会打印-18,但是如果我把最后一行改成
print(insertion_sort(ar[:]) - quickSort(ar[:], 0, n))
它会打印出正确的1(insertion_sort() 的返回值为 9,quickSort() 的返回值为 8)。为什么我不使用列表切片时返回错误的值?
【问题讨论】:
标签: python arrays list python-3.x