백준 11650 python

백준 11650 python

image

커스텀하게 sort하는 문제이기 때문에 def compare 함수가 필요하다
python2에서는 sort함수에 cmp라는 keyword parameter가 있어 아래와 같이 사용가능했지만

points.sort(cmp=compare)

python3에서는 없기 때문에

from functools import cmp_to_key
points.sort(key=cmp_to_key(compare))

와 같이 사용해야한다.

from functools import cmp_to_key

# 1개 수만 비교한다
def compare_num(a, b, ascending=True): 
	flag = 1 if ascending else 0
	if a > b:
		return flag
	elif a < b:
		return 1 - flag
	return 0

# pair를 비교한다.
def compare(p1, p2):
	comp1 = compare_num(p1[0], p2[0])
	if comp1 !=0 :
		return comp1
	return compare_num(p1[1], p2[1])

n = int(input())
points = []
for _ in range(n):
	p = tuple(map(int, input().split()))
	points.append(p)

points.sort(key=cmp_to_key(compare))

위와 같이 compare_num을 두게 되면 각 compare와 compare_num의 역할이 분리되어 더 깔끔하다.

댓글

이 블로그의 인기 게시물

[Linux, Unix] export, echo 명령어 알아보기

뼈속 깊이 이해하기 :: 1. 허프만 코딩

IEEE 754 부동 소수점 반올림과 근사