LoginSignup
1
1

functools使い方 cmp_to_key (abc 308C)

Posted at

atcoder abc308 Cでcmp_to_keyを使った解法があったため、使い方をまとめる。
from functools import cmp_to_key を使用することで、Python のソート
関数(sorted やsortなど)でカスタム比較関数を使うことができる。

cmp_to_key:2つの要素を比較する比較関数(cmp 関数)を受け取り、それを key 関数に変換することができる。比較関数は、2つの引数を取り、それらを比較して -1,0,1 を返す必要がある。

基本的な使い方
from functools import cmp_to_key

# 比較関数
def compare_items(a, b):
    if a > b:
        return 1
    elif a < b:
        return -1
    else:
        return 0

# ソートしたいリスト
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# カスタム比較関数を使ってリストをソート
sorted_list = sorted(my_list, key=cmp_to_key(compare_items))

print(sorted_list)
#sorted_list -> [1, 1, 2, 3, 4, 5, 6, 9]

公式の解法では、同様の手法を用いてcmp関数を作成し、ソートを行っている。

abc308C 解法
from functools import cmp_to_key
def cmp(a, b):
    x, y, i = a
    xx, yy, ii = b
    s = x * yy - y * xx
    return 1 if s > 0 else -1 if s < 0 else 0

N = int(input())
X = []
for i in range(N):
    a, b = map(int, input().split())
    X.append((-a, a + b, i))

X.sort(key = cmp_to_key(cmp))
print(*[i + 1 for x, y, i in X])

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1