【问题标题】:sorting python heaps and lists对python堆和列表进行排序
【发布时间】:2013-12-18 18:12:55
【问题描述】:

我正在尝试解决以下问题

目的:quicheSort算法的实现(没有到位), 它首先使用 quickSort,使用 3 的中值枢轴,直到它 达到由 int(math.log(N,2)) 限制的递归限制。 这里,N 是要排序的初始列表的长度。 一旦达到该深度限制,它就会切换到使用 heapSort 而不是 快速排序。

import heapSort            # heapSort
import qsPivotMedian3
from math import*                 # log2 (for quicksort depth limit)
import testSorts            # run (for individual test run)

def quicheSortRec(lst, limit):
    """
    A non in-place, depth limited quickSort, using median-of-3 pivot.
    Once the limit drops to 0, it uses heapSort instead.
    """
    if len(lst) == 0:
        return lst()
    elif limit > 0:
        quickSort(lst)
    else:
        heapSort(lst)

def quicheSort(lst):
    """
    The main routine called to do the sort.  It should call the
    recursive routine with the correct values in order to perform
    the sort
    """
    if len(lst)== 0:
        return list()
    else:
        limit = float(log(len(lst),[2]))
        return quicheSortRec(lst,limit)

if __name__ == "__main__":
    testSorts.run('quicheSort')

我在使用此代码时遇到的问题是我的限制。我应该将限制设置为 int(log(N,[2]))。但是,python 一直告诉我需要一个浮点数。因此,当我将 int 更改为 float 时,它仍然不断告诉我需要一个 float。

回溯——

le "/Users/sps329/Desktop/quicheSort.py", line 44, in <module>
    testSorts.run('quicheSort')
  File "/Users/sps329/Desktop/testSorts.py", line 105, in run
    performSort(sortType, data, N)
  File "/Users/sps329/Desktop/testSorts.py", line 71, in performSort
    result = sortType.function(dataSet.data)
  File "/Users/sps329/Desktop/quicheSort.py", line 40, in quicheSort
    limit = float(log(len(lst),[2]))
TypeError: a float is required

【问题讨论】:

  • 你能发布回溯吗?
  • [2] 替换为2。根据列表获取日志是没有意义的 ;-)
  • 你使用这个限制的方式很奇怪。它应该在完整列表中计算一次,然后在每个递归级别增加一个计数器并与该值进行比较。
  • 你正在做的甚至不是递归的,顺便说一句

标签: python list sorting heap


【解决方案1】:
        limit = float(log(len(lst),[2]))

[2] 是一个单元素列表。你为什么要制作一个单元素列表?你只想在这里2。我想也许这应该是地板的数学符号,但地板 2 也没有多大意义。

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2012-11-20
    相关资源
    最近更新 更多