Python 快速排序递归不支持的操作数类型 -:'list' 和 'int'`

Python Quicksort Recursion unsupported operand type(s) for -: 'list' and 'int'`

我写的排序程序一直有问题,错误

Traceback (most recent call last):
  File "/Users/Shaun/PycharmProjects/Sorts/BubbleSort.py", line 117, in <module>
    sorted = quick_sort(unsorted, 0, len(unsorted - 1))
TypeError: unsupported operand type(s) for -: 'list' and 'int'

发生在我​​的快速排序的函数调用中,见下文

print("You chose Quick Sort\n")
sorted = []
sorted = quick_sort(unsorted, 0, len(unsorted - 1))

这是带有输入参数的快速排序函数

def quick_sort(list, leftBound, rightBound) -> object:

    leftBound = int(leftBound)
    rightBound = int(rightBound)
    pivot = int((list[math.floor(leftBound + rightBound / 2)]))
    print(pivot)
    while leftBound <= rightBound:

        # while bigger numbers are above pivot and lower are below
        # update bounds left + , right -
        while list[leftBound] < pivot:
            leftBound += 1
        while list[rightBound] > pivot:
            rightBound -= 1

        if (leftBound <= rightBound):
            list[rightBound], list[leftBound] = list[leftBound], list[rightBound]
            leftBound += 1
            rightBound -= 1
    if (leftBound < rightBound):
         quick_sort(list, leftBound, rightBound)
    if (rightBound < leftBound):
        quick_sort(list, leftBound, rightBound)

    print(list)
    return list
len(unsorted - 1)

应该是

len(unsorted) - 1

错误信息中写的很清楚:

TypeError: unsupported operand type(s) for -: 'list' and 'int'

这意味着您正在执行一个操作,该操作是“-”(如错误消息中所述:"for -"),操作对象的类型不受此操作支持。

所以您是从 LIST 类型中减去 INT 类型。

您需要更改该行:

len(unsorted - 1)

len(unsorted) - 1