猿问

Python 快速排序类型错误

以下是我的代码抛出的错误:


 File "python", line 39, in <module>

  File "python", line 8, in quicksort

  File "python", line 8, in quicksort

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

下面是我的快速排序代码:


#!/usr/bin/python

# -*- coding: utf-8 -*-


def quicksort(arr, beg, end):

    if beg < end:

        pivot = partition(arr, beg, end)

        quicksort(arr, beg, pivot - 1)

        quicksort(arr, pivot + 1, end)


def partition(arr, beg, end):

    left = beg

    right = end

    loc = beg

    while arr[loc] <= arr[right] and loc != right:

        right = right - 1

    if loc == right:

        return loc

    elif arr[loc] > arr[right]:

        (arr[loc], arr[right]) = (arr[right], arr[loc])

        loc = right


    while arr[loc] >= arr[left] and loc != left:

        left = left + 1

    if loc == left:

        return loc

    elif arr[loc] < arr[left]:

        (arr[loc], arr[left]) = (arr[left], arr[loc])

        loc = left


y = [9,7,5,1,5]

quicksort(y, 0, 4)

print(y)


达令说
浏览 129回答 2
2回答

宝慕林4294392

您不能从不同类型(None和int)中减去 2 个变量。你得到了,None因为不是所有的partition函数路径都返回一些东西。我return在它的末尾添加了一个对我来说最有意义的声明:#!/usr/bin/python# -*- coding: utf-8 -*-def quicksort(arr, beg, end):&nbsp; &nbsp; if beg < end:&nbsp; &nbsp; &nbsp; &nbsp; pivot = partition(arr, beg, end)&nbsp; &nbsp; &nbsp; &nbsp; quicksort(arr, beg, pivot - 1)&nbsp; &nbsp; &nbsp; &nbsp; quicksort(arr, pivot + 1, end)def partition(arr, beg, end):&nbsp; &nbsp; left = beg&nbsp; &nbsp; right = end&nbsp; &nbsp; loc = beg&nbsp; &nbsp; while arr[loc] <= arr[right] and loc != right:&nbsp; &nbsp; &nbsp; &nbsp; right = right - 1&nbsp; &nbsp; if loc == right:&nbsp; &nbsp; &nbsp; &nbsp; return loc&nbsp; &nbsp; elif arr[loc] > arr[right]:&nbsp; &nbsp; &nbsp; &nbsp; (arr[loc], arr[right]) = (arr[right], arr[loc])&nbsp; &nbsp; &nbsp; &nbsp; loc = right&nbsp; &nbsp; while arr[loc] >= arr[left] and loc != left:&nbsp; &nbsp; &nbsp; &nbsp; left = left + 1&nbsp; &nbsp; if loc == left:&nbsp; &nbsp; &nbsp; &nbsp; return loc&nbsp; &nbsp; elif arr[loc] < arr[left]:&nbsp; &nbsp; &nbsp; &nbsp; (arr[loc], arr[left]) = (arr[left], arr[loc])&nbsp; &nbsp; &nbsp; &nbsp; loc = left&nbsp; &nbsp; return locy = [9,7,5,1,5]quicksort(y, 0, 4)print(y)&nbsp; # >>> [1, 5, 5, 7, 9]但是,我没有检查每个场景的代码逻辑的正确性。您可以查看此线程以查看 Python 中快速排序的实现。

FFIVE

从函数中partition你没有返回任何东西。您已将其分配给pivot变量。这就是问题所在。照顾好您应该返回的值。
随时随地看视频慕课网APP

相关分类

Python
我要回答