首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Quickselect不打印/返回枢轴

Python Quickselect不打印/返回枢轴
EN

Stack Overflow用户
提问于 2013-10-07 22:16:38
回答 2查看 1.2K关注 0票数 1

以下是quickselect的代码

代码语言:javascript
复制
def quickSelect(lst, k):
if len(lst) != 0:
    pivot = lst[(len(lst)) // 2]
    smallerList = []
    for i in lst:
        if i < pivot:
            smallerList.append(i)
    largerList = []
    for i in lst:
        if i > pivot:
            largerList.append(i)
    count = len(lst) - len(smallerList) - len(largerList)
    m = len(smallerList)
    if k >= m and k < m + count:
        return pivot
        print(pivot)
    elif m > k:
        return quickSelect(smallerList, k)
    else:
        return quickSelect(largerList, k-m-count)

我的问题是,它运行时没有任何错误或任何东西,但是当它完成时,我希望它能输出一些东西到python (在这个特定的例子中,是列表的中间值),但是我什么也没有得到。我在这里做错什么了吗?

至于我为第一和第一输入的内容..。

  • lst = 70,120,170,200
  • K=len(1) // 2

我也尝试过一些不同的k值,但都没有用。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-07 23:18:03

代码语言:javascript
复制
def quickSelect(lst, k):
    if len(lst) != 0:
        pivot = lst[(len(lst)) // 2]
        smallerList = []
        for i in lst:
            if i < pivot:
                smallerList.append(i)
        largerList = []
        for i in lst:
            if i > pivot:
                largerList.append(i)
        count = len(lst) - len(smallerList) - len(largerList)
        m = len(smallerList)
        if k >= m and k < m + count:
            return pivot
            print(pivot)
        elif m > k:
            return quickSelect(smallerList, k)
        else:
            return quickSelect(largerList, k-m-count)

lst = [70, 120, 170, 200]
k = len(lst) // 2

print(quickSelect(lst, k))

产生

代码语言:javascript
复制
>>> 170

我唯一纠正的就是缩痕。

票数 0
EN

Stack Overflow用户

发布于 2014-08-26 16:10:54

您可以使用列表理解优化此算法。而且我觉得你不需要数数..。

代码语言:javascript
复制
 def quickSelect(seq, k):
    # this part is the same as quick sort
    len_seq = len(seq)
    if len_seq < 2: return seq

    ipivot = len_seq // 2
    pivot = seq[ipivot]

    smallerList = [x for i,x in enumerate(seq) if x <= pivot and  i != ipivot]
    largerList = [x for i,x in enumerate(seq) if x > pivot and  i != ipivot]

    # here starts the different part
    m = len(smallerList)
    if k == m:
        return pivot
    elif k < m:
        return quickSelect(smallerList, k)
    else:
        return quickSelect(largerList, k-m-1)




if __name__ == '__main__':
    # Checking the Answer
    seq = [10, 60, 100, 50, 60, 75, 31, 50, 30, 20, 120, 170, 200]

    # we want the middle element
    k = len(seq) // 2

    # Note that this only work for odd arrays, since median in
    # even arrays is the mean of the two middle elements
    print(quickSelect(seq, k))
    import numpy
    print numpy.median(seq)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19235747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档