【问题标题】:Quicksort program - it's giving me type-error快速排序程序 - 它给了我类型错误
【发布时间】:2021-06-04 02:01:09
【问题描述】:
def quick_sort(sequence):
    length = len(sequence)
    if length <= 1:
        return
    else:
        pivot = sequence.pop()

    items_g = []
    items_l = []

    for item in sequence:
        if item > pivot:
            items_g.append(item)
        else:
            items_l.append(item)

    return quick_sort(items_l) + [pivot] + quick_sort(items_g)


print(quick_sort([5, 89, 7, 41, 2]))

【问题讨论】:

  • 如果长度
  • (像这样的非就地分区交换排序将有不利的资源饥饿。基本情况后面的else: 是不必要的。)

标签: python-3.x algorithm sorting quicksort


【解决方案1】:

您必须返回一个空列表,而不是 None

def quick_sort(sequence):
    length = len(sequence)
    if length <= 1:
        return []
    else:
        pivot = sequence.pop()

    items_g = []
    items_l = []

    for item in sequence:
        if item > pivot:
            items_g.append(item)
        else:
            items_l.append(item)

    return quick_sort(items_l) + [pivot] + quick_sort(items_g)


print(quick_sort([5, 89, 7, 41, 2]))

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 2021-10-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多