【问题标题】:Python Quicksort Recursion unsupported operand type(s) for -: 'list' and 'int'`Python Quicksort Recursion不支持的操作数类型用于-:'list'和'int'`
【发布时间】:2015-05-10 10:53:43
【问题描述】:

我正在编写的排序程序出现问题,错误

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

【问题讨论】:

    标签: python function sorting call


    【解决方案1】:

    错误信息中明确说明:

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

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

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

    您需要从以下位置更改该行:

    len(unsorted - 1)
    

    len(unsorted) - 1
    

    【讨论】:

      【解决方案2】:
      len(unsorted - 1)
      

      应该是

      len(unsorted) - 1
      

      【讨论】:

        猜你喜欢
        • 2018-10-19
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 2012-12-12
        • 2016-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多