Python变量混淆

2024-09-27 00:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在阅读有关Quickselect算法的文章,并找到了一些有用的代码。 我不明白pivotIndex是如何声明两次而不是重写的。 我想澄清一下Python是如何不过度编写pivotIndex的

我删除了pivotIndex的第二个声明,并收到随机输出

def qselect(k, array):
    n = k-1

    def partition(left, right, pivotIndex):
        pivotValue = array[pivotIndex]

        array[pivotIndex], array[right] = array[right], array[pivotIndex]
        storeIndex = left
        for i in range(left, right):
            if array[i] < pivotValue:
                array[storeIndex], array[i] = array[i], array[storeIndex]
                storeIndex += 1

        array[right], array[storeIndex] = array[storeIndex], array[right]
        return storeIndex

    def select(left, right):
        if left == right:
            return array[left]
        pivotIndex = random.randint(left, right)
        pivotIndex = partition(left, right, pivotIndex)

        if n == pivotIndex:
            return array[n]
        elif n < pivotIndex:
            return select(left, pivotIndex-1)
        else:
            return select(pivotIndex+1, right)

    return select(0, len(array)-1)

Tags: right算法声明returnifdefarrayleft
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:41

它被覆盖了

pivotIndex = random.randint(left, right)
pivotIndex = partition(left, right, pivotIndex)

这里所发生的是,我们在左、右值的范围内找到一个pivotIndex的随机值。 我们将该值用作函数分区的参数,并将返回值赋给pivotIndex

相关问题 更多 >

    热门问题