python functools.cmp_to_key()使用 Leetcode 179 最大数 剑指 Offer 45 把数组排成最小的数

一、python3 functools.cmp_to_key

cmp_to_key() 排序比较方法

  • cmp是比较的意思(compare),cmp函数在python2中使用,Python 3 为了语言的简洁性去掉了 cmp 这个参数,在 Python3 重自定义比较函数需要通过 cmp_to_key 将比较函数转化成 key 可以接受的参数。

  • Python 3 中一些接受 key的函数中(例如sorted,min,max,heapq.nlargest,itertools.groupby),key仅仅支持一个参数,无法实现两个参数之间的对比。采用 cmp_to_key函数,可以接受两个参数,对两个参数做处理,比如做和做差,转换成一个参数,就可以应用于 key 关键字了。

from functions import cmp_to_key

cmp_to_key()是python内置模块functools的一个高阶函数,将(Python2)的比较函数转换为新式的key function,针对Iterable.sort()或者sorted(Iterable)的稍微复杂一点的对象排序,在类似sorted(),min(),max(), heapq.nlargest, heapq.nsmallest()等函数的key参数中使用。

使用:
比较函数意为一个可调用对象,该对象接受两个参数并比较它们,结果为小于则返回一个负数,相等则返回零,大于则返回一个正数。key function 则是一个接受一个参数,并返回另一个用以排序的值的可调用对象。通过这个函数可以把一个 cmp 函数(它支持两个参数,排序过程是一个对比过程,对比在两个元素之间进行)变成一个 key 函数,从而可以实现自定义排序规则。

以python3的sorted()函数和列表的sort()方法为例:

[ ].sort
<function list.sort(*, key=None, reverse=False)>
sorted()
<function sorted(iterable, /, *, key=None, reverse=False)>

两种方法不再支持 cmp 参数,而支持了 key 参数,它们的作用都是自定义一个排序方法。
它们的区别是:

  • key 参数:Python 3 支持,接受的函数(入参为每个元素)返回值(对这个元素的计算),表示此元素的权值,sorted将按照权值大小进行排序
  • cmp 参数:Python 2支持,接受的函数是元素中的所有需要对比的两个元素,这个函数定义大于(一般返回1)、小于(-1)、等于逻辑(1),最后根据这些比较逻辑排序

二、Leetcode

注:我们需要思考一个问题:两个int型字符串是可以比较大小的吗?
答:可以比较,但是需要在特定的条件下进行比较,特定的条件是什么呢?即需要在两个字符串等长时比较,当字符串长度相同时,程序按照字符串的各个字符从前向后逐个比较,即相当于先比较百分位,在比较十分位最后比较个位,所以在字符串等长的情况下,字符串大,那么对应的整形也就更大,但两个不等长的字符串就没有这个结论了,例子如下:
例子:

print("95056">"94986")
# True
print("2">"10") #字符串不等长,没有可比性
# True
1、Leetcode179 最大数

在这里插入图片描述
思路:

  • 先把nums中的数字转换为字符串,形成字符串数组nums_str
  • 比较两个字符串x,y的拼接结果,x+y和y+x哪个更大,从而确定x和y谁排在前面,将nums_str降序排序(sort(reverse=False),默认为升序排序)
  • 把整个数组排序的结果拼成一个字符串,并且返回

代码如下:

import functools
class Solution:
	def largestNumber(self, nums:List[])->str:
		nums_str = list(map(str, nums)) # 将nums转换为str,并转换为list
		compare = lambda x,y: 1 if x+y<y+x else -1
		nums_str.sort(key=functools.cmp_to_key(compare))
		res = "".join(nums_str)
		# 考虑特殊情况,如 [0,0]则直接返回"0"
		if res[0]=="0":
			return "0"
		return res

当cmp_to_key返回1时,则x,yl两元素互换,返回-1时,两元素不变
对于list中多个元素的情况,使用functools.cmp_to_key()的执行情况较为复杂,我们以nums = [10,2]为例,
首先比较"102" 与 “210”,“102”<“210”,故返回1,如果返回1,则互换两个值,此时nums_str=[“2”,“10”]

2、剑指 Offer 45 把数组排成最小的数

在这里插入图片描述
这道题是最大值的反例,只需要将lambda(lambda叫做匿名函数)中的大于号变为小于号即可

from functools import cmp_to_key
class Solution:
	def minNumber(self, nums: List[int]) -> str:
		nums_str = list(map(str, nums))
		compare = lambda x,y: 1 if x+y>y+x else -1
		nums_str.sort(key=cmp_to_key(compare))
		res =  "".join(nums_str)
		if res[0]=="0":
			return "0"
		return res
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The `functools.cmp_to_key` function is a utility function in Python's `functools` module that helps convert a comparison function to a key function. In Python, sorting a list of objects requires a way to compare the objects. This is done by providing a comparison function that takes two objects as input and returns `-1`, `0`, or `1` depending on whether the first object is less than, equal to, or greater than the second object. However, some sorting functions in Python (such as the `sorted` function) require a key function instead of a comparison function. A key function takes a single object as input and returns a value that can be used for sorting. The `cmp_to_key` function helps convert a comparison function to a key function by returning a new function that takes a single object as input and returns a tuple `(comparison_result, object)` where `comparison_result` is the result of calling the original comparison function with the input object and another object, and `object` is the input object itself. This tuple can then be used for sorting. Here's an example of how to use `cmp_to_key`: ``` from functools import cmp_to_key def compare_length(str1, str2): if len(str1) < len(str2): return -1 elif len(str1) > len(str2): return 1 else: return 0 strings = ['cat', 'dog', 'elephant', 'a', 'zebra'] sorted_strings = sorted(strings, key=cmp_to_key(compare_length)) print(sorted_strings) # Output: ['a', 'cat', 'dog', 'zebra', 'elephant'] ``` In this example, we define a comparison function `compare_length` that compares the lengths of two strings. We then use `cmp_to_key` to convert this comparison function to a key function, and pass it to the `sorted` function to sort a list of strings by length. The resulting sorted list is `['a', 'cat', 'dog', 'zebra', 'elephant']`.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值