functools.cmp_to_key(func)
Transform an old-style comparison function to a key function. Used with tools that accept key functions (such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby()). This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.
A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than. A key function is a callable that accepts one argument and returns another value to be used as the sort key.
Example:
sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
New in version 3.2.
다음 문제를 풀 때 활용할 수 있는 IDEA.
import functools
def compareString(s1, s2):
a = s1 + s2
b = s2 + s1
if a > b:
return 1
elif a == b:
return 0
elif a < b:
return -1
def solution(numbers):
answer = ''
numbers = [str(x) for x in numbers]
numbers.sort(key=functools.cmp_to_key(compareString), reverse=True)
answer = ''.join(numbers)
return answer
'Coding Test > 정리' 카테고리의 다른 글
[Swift] Swift를 이용한 문제 풀이 (0) | 2022.06.15 |
---|---|
[python] list pop VS pop first (0) | 2022.03.08 |
[python] Dictionary, Counter (0) | 2022.02.21 |