【问题标题】:Fastest way to sort list of dates when adding to the list添加到列表时对日期列表进行排序的最快方法
【发布时间】:2012-05-05 04:43:00
【问题描述】:

我正在编写类似于任务调度程序的东西。我有两组任务,有些是固定的(给定开始和结束日期和时间),有些不是固定的(给定开始日期和时间以及持续时间)。

非固定任务受到固定任务的影响,因此如果非固定任务与固定任务重叠,非固定任务将延长其持续时间。

我从一个元组列表开始,其中第一项是开始日期,第二项是该固定任务的 ID,如下所示:

[(2012-04-30, 1), (2012-05-01, 5), (2012-05-04, 2)]

然后我有另一个列表,由用户排序,非固定任务。我的想法是我将遍历这个列表,在那个循环中我将遍历第一个列表以查找可能与此任务重叠的任务,并且可以确定哪些任务可以扩展非固定任务.

我在这里寻求您的帮助。现在我知道了这个非固定任务的计算开始和结束时间,我需要将其视为“固定”,以便它影响其余的非固定任务。

我可以将此任务添加到第一个固定任务列表中并再次对其进行排序,但这意味着我每次添加任务时都会对列表进行排序。

我可以遍历第一个列表并找到应该插入此任务的点,然后将其插入那里。但是,如果它的位置在列表的前面,则需要花费时间将所有其他项目移到一个位置。如果它的位置在列表的后面,我将不得不遍历很多元素才能到达正确的位置。

所以,我不赞成使用这些选项中的任何一个。这里真正的问题是:在添加内容的同时保持列表排序的最佳方式是什么?还是有更好的方法来完成这一切?

【问题讨论】:

  • 请记住,如果您要对大部分已经排序的数据进行排序,那么好的排序算法(例如 Python 使用的Timsort)不需要做很多额外的工作。跨度>
  • bisect 模块 docs.python.org/library/bisect.html 怎么样?
  • @MichaelMior 除最后一个元素外,所有内容都将被排序。
  • @Fenikso 通过阅读概述,听起来这可能是我会使用的库。是否有任何与另一种方法的比较?我想知道它相对来说有多快。
  • @STH - 抱歉,我从未使用过它,我最近才听说它,你的问题敲响了警钟。它应该只实现插入排序。它应该进行 O(log n) 二进制搜索和 O(n) 插入。

标签: python list datetime sorting


【解决方案1】:

Heap Queue 是你的朋友。来自维基百科:

堆通常执行的操作有:

  • create-heap:创建一个空堆
  • find-max:找到一个最大堆的最大项
  • delete-max:删除一个最大堆的根节点
  • increase-key:在最大堆中更新一个键
  • 插入:向堆中添加新键
  • merge:连接两个堆以形成一个有效的新堆,其中包含所有 两者的元素。

有一个内置的Python Heap Queue 实现。堆针对 1) 删除最大元素,2) 插入新元素以保持堆排序进行了优化。

【讨论】:

  • 但是扫描堆以查找重叠的“固定”任务仍然很昂贵。甚至比排序列表更昂贵。
  • 这可行,但听起来你主要是在推送和弹出堆,但我不想随时弹出堆,因为任务不会离开系统(除非删除)。
【解决方案2】:

这里是使用 bisect 并与使用部分排序列表的排序进行比较的示例。对分解决方案显然胜出:

import bisect
import random
import timeit


def bisect_solution(size=10000):
    lst = []
    for n in xrange(size):
        value = random.randint(1, 1000000)
        bisect.insort_left(lst, value)
    return lst


# Cut out of the bisect module to be used in bisect_solution2()
def insort_left(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the left of the leftmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    a.insert(lo, x)


def bisect_solution2(size=10000):
    lst = []
    for n in xrange(size):
        value = random.randint(1, 1000000)
        insort_left(lst, value)
    return lst


def sort_solution(size=10000):
    lst = []
    for n in xrange(size):
        value = random.randint(1, 1000000)
        lst.append(value)
        lst.sort()
    return lst


t = timeit.timeit('bisect_solution()', 'from __main__ import bisect_solution', number = 10)
print "bisect_solution: ", t

t = timeit.timeit('bisect_solution2()', 'from __main__ import bisect_solution2', number = 10)
print "bisect_solution2: ", t

t = timeit.timeit('sort_solution()', 'from __main__ import sort_solution', number = 10)
print "sort_solution: ", t

bisect_solution2() 与 bisect_solution() 几乎相同——只是从模块中复制了代码。其他人应该解释为什么需要更多时间:)

这里要修改 bisect_solution2(),以便 cmp() 函数能够比较元组。

它在我的电脑上显示以下结果:

bisect_solution:  0.637892403587
bisect_solution2:  0.988893038133
sort_solution:  15.3521410901

下面是对日期为字符串的元组采用的二等分解决方案:

import random
import timeit


def random_date_tuple():
    s1 = '{0}-{1:02}-{2:02}'.format(random.randint(2000, 2050),
                                    random.randint(1, 12),
                                    random.randint(1, 31))
    e2 = random.randint(1,50)
    return (s1, e2)


def my_cmp(a, b):
    result = cmp(a[0], b[0])   # comparing the date part of the tuple
    if result == 0:
        return cmp(a[1], b[1]) # comparint the other part of the tuple
    return result


def my_insort_left(a, x, cmp=my_cmp, lo=0, hi=None):
    """The bisect.insort_left() modified for comparison of tuples."""

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if cmp(a[mid], x) < 0: 
            lo = mid+1
        else: 
            hi = mid
    a.insert(lo, x)


def bisect_solution3(size=1000):
    lst = []
    for n in xrange(size):
        value = random_date_tuple()
        my_insort_left(lst, value)
    return lst


def sort_solution(size=1000):
    lst = []
    for n in xrange(size):
        value = random_date_tuple()
        lst.append(value)
        lst.sort(cmp=my_cmp)
    return lst


t = timeit.timeit('bisect_solution3()', 'from __main__ import bisect_solution3', number = 10)
print "bisect_solution3: ", t

t = timeit.timeit('sort_solution()', 'from __main__ import sort_solution', number = 10)
print "sort_solution: ", t

print bisect_solution3()[:10]

请注意,由于排序解决方案非常慢,因此列表大小比前一个小 10 倍。它打印:

bisect_solution3:  0.223602245968
sort_solution:  3.69388944301
[('2000-02-01', 20), ('2000-02-13', 48), ('2000-03-11', 25), ('2000-03-13', 43),
 ('2000-03-26', 48), ('2000-05-04', 17), ('2000-06-06', 23), ('2000-06-12', 31),
 ('2000-06-15', 15), ('2000-07-07', 50)]

【讨论】:

  • 感谢您的演示。
  • +1 用于定时示例。顺便说一句:bisect.insort_left 可能在 CPython 中用 C 语言实现 - 这就是它更快的原因。
  • @Fenikso:你是对的。您可以在 /usr/lib/python2.6/bisect.pyC:\Python26\Lib\bisect.py(或 Python 2.7 或 Python 3.2 的类似名称)中找到该模块。它很短。您可以找到 # Overwrite above definitions with a fast C implementation 以及从 _bisect 模块导入它的命令(注意下划线)。但在这种情况下,.py 实现一点也不差!
【解决方案3】:

我可以遍历第一个列表并找到该任务的位置 应该插入,然后将其插入那里。但是,如果它的位置是 在列表的前面,时间花在将所有其他项目移到一项上 地方。如果它的位置在列表中,我将不得不循环 通过很多元素到达正确的地方。

使用binary search 可以在 O(log n) 中找到将内容插入排序列表的正确位置。插入仍然是 O(n)。

还有更复杂的数据结构,如B-Trees,允许在 O(log n) 中插入和搜索。看看thisthis

【讨论】:

  • 这是基于每次内存访问都需要相同时间的理论。现实是不同的。处理器有大缓存,复杂的图结构可能会导致内存页面错误......
  • 在这种情况下,如果我正在寻找替代列表的方法,那么我肯定会选择您提供的“blist”选项。在每种情况下,它似乎都比普通列表具有可比性和/或更快:stutzbachenterprises.com/performance-blist
【解决方案4】:

这里真正的问题是:在向列表添加内容时保持列表排序的最佳方法是什么?

Insertion Sort 是要走的路。但你可能不喜欢它,因为你已经知道了。接下来你可以做的就是这个,

  1. 添加时不要排序。
  2. 当您获得项目时,对其进行排序和缓存。下次请求时从以前的缓存中显示。
  3. 添加任何新项目时使缓存无效。

我不是 Python 程序员,但我可以通过 PHP 类给你一些想法。

class SortedList(){
    public $list = array();
    private $cached_list;

    public function add($item){
        array_push($this->list, $item);
        $this->sorted = false;
    }
    public function get(){
        if($this->sorted==true){
            return $this->cached_list;
        }

        // sort the array;

        // copying the list to cached list and sort it
        $this->cached_list = $this->list;
        sort($this->cached_list);

        // set the flag
        $this->sorted = true;
        return $this->cached_list
    }

}

【讨论】:

    猜你喜欢
    • 2012-03-29
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多