为什么我的python归并排序算法不工作?



我想对实例列表(ClientInfo - class)的名称使用归并排序算法进行排序。
我试图在Python中构建算法,但当我运行它时,我有这个错误:错误我怎么解它?


def mergesort(lst, *, key=lambda x: x, reverse=False):
"""
MergeSort implementation
:param lst: the list that will be sorted
:param key: the function by witch it is sorted
:param reverse: True - ascending sort, False - descending sort
:return: return the sorted list
"""
if len(lst) > 1:
pivot = len(lst) // 2
left_half = lst[:pivot]
right_half = lst[pivot:]
mergesort(left_half)
mergesort(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
if reverse is False:  # ascending sort
if key(left_half[i]) < key(right_half[j]):
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1
elif reverse is True:  # descending sort
if key(left_half[i]) < key(right_half[j]):
lst[k] = right_half[j]
j += 1
else:
lst[k] = left_half[i]
i += 1
k += 1

这里我调用函数
顺便说一句:如果我这样写函数,它可以工作,但我希望它是通用的。

我试图在Python中构建算法,但当我运行它时,我有这个错误:错误我如何解决它?

你需要重载<操作符,这里有一个例子:>

class ClientInfo:
name = None
def __init__(self, name):
self.name = name
# overloading of operator <
def __lt__(self, c):
return self.name < c.name
# overloading of print
def __str__(self):
return "Name: {}".format(self.name)

v = [ClientInfo("c"), ClientInfo("z"), ClientInfo("a")]
for c in sorted(v):
print(c)

最新更新