相关疑难解决方法(0)

如何观看 Timsort 移动元素?

我想对列表进行排序并观察/可视化 Python 的排序算法Timsort如何移动元素。

第一次尝试list每次更改后都会打印自己的子类:

class List(list):
    def __setitem__(self, index, value):
        list.__setitem__(self, index, value)
        print(self)
Run Code Online (Sandbox Code Playgroud)

这在我自己更改元素时有效,但在sort...期间没有:

>>> a = List([None] * 2)
>>> a[0] = 'S'
['S', None]
>>> a[1] = 'P'
['S', 'P']
>>> a.sort()
>>>
Run Code Online (Sandbox Code Playgroud)

第二次尝试a在每次比较元素时打印列表(在全局变量中):

class Str(str):
    def __lt__(self, other):
        print(a)
        return other > self
Run Code Online (Sandbox Code Playgroud)

那确实有些作用,但列表总是......空的?

>>> a = list(map(Str, 'test'))
>>> a.sort()
[]
[]
[]
[]
[]
[]
>>>
Run Code Online (Sandbox Code Playgroud)

为什么这些尝试会失败,有没有办法观察 Timsort 正在做什么?

python sorting timsort

3
推荐指数
1
解决办法
212
查看次数

标签 统计

python ×1

sorting ×1

timsort ×1