Python 使用“key”排序功能不足
一方面,很容易看出给定一个关键函数,我们可以轻松地实现一种使用比较函数执行相同操作的排序。简化如下:
def compare(x,y):
return key(x) - key(y)
另一方面,我们如何确定我们不会通过使用键通过元素映射来限制每种排序而丢失潜在的排序?例如,假设我想对长度为 2 的元组 (x,y) 的列表进行排序,我坚持使用以下比较方法:
def compare(tup1,tup2):
if (tup1[1] < tup2[0]):
return -1
if (tup1[0] % 2 == 0):
return 1
if (tup1[0] - tup2[1] < 4):
return 0
else:
return 1
现在告诉我如何将此比较转换为相应的“键”函数,以便我的排序算法继续同样的方式?这不是一个人为的例子,因为这些类型的定制排序出现在搜索过程中的对称性破坏算法中,并且非常重要。
On one hand it is easy to see given a key function, one can easily implement a sort that does the same thing using a compare function. The reduction is as follows:
def compare(x,y):
return key(x) - key(y)
On the other, how do we know for sure we are not losing potential sortings by restricting every kinds of sort by a map of elements using key? For instance, suppose I want to sort a list of length 2 tuples (x,y) where I insist the following compare method:
def compare(tup1,tup2):
if (tup1[1] < tup2[0]):
return -1
if (tup1[0] % 2 == 0):
return 1
if (tup1[0] - tup2[1] < 4):
return 0
else:
return 1
Now tell me how do I translate this compare into a corresponding "key" function such that my sorting algorithm proceed the same way? This is not a contrived example as these kinds of customised sorting show up in symmetry breaking algorithms during a search, and is very important.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
functools.cmp_to_key
,这将保证与你的比较函数。此函数的源代码可以在 Python 的排序方法文档中找到。Use
functools.cmp_to_key
, this will guarantee the same sorting behavior as your compare function. The source for this function can be found on Python's Sorting How To document.