【问题标题】:Mutability of Python list in a recursive algorithm递归算法中 Python 列表的可变性
【发布时间】:2016-06-13 12:12:30
【问题描述】:

我编写了这个就地快速排序算法,但是修改后的数组没有传递给父调用。我是 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

【问题讨论】:

  • 您的输入 (testerText.txt) 是什么样的?
  • 糟糕,感谢您的评论,刚刚表明
  • 发布了解决方案。确保捕获递归函数返回的结果全部

标签: python algorithm sorting recursion quicksort


【解决方案1】:

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

输出:

[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]

【讨论】:

  • 谢谢 Yash,来自 SF 的问候
【解决方案2】:

当您使用范围为列表下标时,它会创建该列表的副本并将其返回。

因此,当您将a[:i] 传递给您的函数时,不会考虑任何更改。

当您执行a[i] = 3 时,它会更改您的列表。

因此,您可能需要更改代码,以便您的函数可以直接将 a 作为输入和索引 i。

【讨论】:

  • 我刚刚意识到你抓住了问题的核心,非常感谢您的解释
  • 没问题,乐于助人。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2020-07-04
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2012-09-13
  • 2017-06-24
  • 1970-01-01
相关资源
最近更新 更多