[英]Mutability of Python list in a recursive algorithm
I coded up this in-place quicksort algorithm, however the modified array is not being passed up to the parent call. 我对这种快速排序算法进行了编码,但是修改后的数组并未传递给父调用。 I am new to Python and don't understand well the pass by value/reference, mutable/immutable stuff etc. Any explanation guidance would be great! 我是Python的新手,对值/引用,可变/不可变的东西等的传递不甚了解。任何解释指导都将很棒!
def quickSortPartition(a, l, r):
if len(a) < 2:
return a
else:
print a, l, r
p = a[l]
i = l + 1
for j in range(l + 1, r+1):
if a[j] < p:
temp = a[i]
a[i] = a[j]
a[j] = temp
i = i + 1
temp = a[l]
a[l] = a[i - 1]
a[i - 1] = temp
firstPartition = a[:i-1]
pivot = a[i-1]
secondPartition = a[i:]
if len(a[:i-1]) > 1:
quickSortPartition(a[:i-1], 0, len(a[:i-1])-1)
if len(a[i:]) > 1:
quickSortPartition(a[i:], 0, len(a[i:])-1)
return a
lines = [3, 8, 2, 5, 1, 4, 7, 6]
# print lines
quickSorted = quickSortPartition(lines, 0, len(lines)-1)
print quickSorted
Basically, quickSortPartition returns a sorted list, so when you make a recursive call to quickSortPartition, make sure to capture the returned values 基本上,quickSortPartition返回一个排序列表,因此当您递归调用quickSortPartition时,请确保捕获返回的值
def quickSortPartition(a, l, r):
if len(a) < 2:
return a
else:
print a, l, r
p = a[l]
i = l + 1
for j in range(l + 1, r+1):
if a[j] < p:
temp = a[i]
a[i] = a[j]
a[j] = temp
i = i + 1
temp = a[l]
a[l] = a[i - 1]
a[i - 1] = temp
firstPartition = a[:i-1]
pivot = a[i-1]
secondPartition = a[i:]
if len(a[:i-1]) > 1:
a[:i-1] = quickSortPartition(a[:i-1], 0, len(a[:i-1])-1)
if len(a[i:]) > 1:
a[i:] = quickSortPartition(a[i:], 0, len(a[i:])-1)
return a
lines = [3, 8, 2, 5, 1, 4, 7, 6]
# print lines
quickSorted = quickSortPartition(lines, 0, len(lines)-1)
print quickSorted
Output: 输出:
[3, 8, 2, 5, 1, 4, 7, 6] 0 7
[1, 2] 0 1
[5, 8, 4, 7, 6] 0 4
[8, 7, 6] 0 2
[6, 7] 0 1
[1, 2, 3, 4, 5, 6, 7, 8]
When you subscript a list with a range, it creates a copy of the list and return it. 用范围下标列表时,它会创建列表的副本并返回。
So when you pass a[:i]
to your function, no change will be taken into account. 因此,当您将a[:i]
传递给函数时,不会考虑任何更改。
When you do a[i] = 3
, it will change your list. 当您执行a[i] = 3
,它将更改您的列表。
So you might want to change your code so that your function can take a directly as input and your index i. 因此,您可能需要更改代码,以便您的函数可以直接将a作为输入和索引i。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.