Python Quicksort Recursion不支持的操作数类型 - :'list'和'int'`

时间:2022-09-10 22:06:12

I have been having issues with a sorting program I am writing, the error

我一直在处理我正在编写的排序程序的问题,错误

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'

occurs at the function call for my quicksort see below

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

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

Here is the quicksort function with its input parameters

这是带有输入参数的quicksort函数

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

2 个解决方案

#1


It is clearly stated in the Error message:

错误消息中明确说明:

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

It means you are doing an operation, which is "-" (as stated in the error message: "for -") on operands whose type(s) not supported by this Operation.

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

So you were subtracting an INT type from a LIST type.

所以你从LIST类型中减去INT类型。

you need to change that line from:

你需要改变这一行:

len(unsorted - 1)

to

len(unsorted) - 1

#2


len(unsorted - 1)

should be

len(unsorted) - 1

#1


It is clearly stated in the Error message:

错误消息中明确说明:

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

It means you are doing an operation, which is "-" (as stated in the error message: "for -") on operands whose type(s) not supported by this Operation.

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

So you were subtracting an INT type from a LIST type.

所以你从LIST类型中减去INT类型。

you need to change that line from:

你需要改变这一行:

len(unsorted - 1)

to

len(unsorted) - 1

#2


len(unsorted - 1)

should be

len(unsorted) - 1