코딩테스트
[구름] 단어장 만들기 (python)
hammii
2024. 11. 24. 23:55
문제
구름LEVEL
난이도별 다양한 문제를 해결함으로써 SW 역량을 향상시킬 수 있습니다.
level.goorm.io
풀이
from functools import cmp_to_key
N, K = map(int, input().split())
arr = [input() for _ in range(N)]
def compare(a, b):
if len(a) < len(b):
return -1
elif len(a) == len(b):
if a < b:
return -1
else:
return 1
else:
return 1
arr = sorted(arr, key=cmp_to_key(compare))
print(arr[K-1])
python 에서는 정렬할 때 sorted 내장함수를 사용할 수 있는데, 여기서 key는 무엇을 기준으로 정렬할 것인지를 나타낸다.
변수를 넣을 수도 있고 함수를 넣을 수도 있는데
함수를 넣는 경우 cmp_to_key(함수명) 으로 사용할 수 있다.
두 문자열의 길이를 먼저 비교한 후, 길이가 같은 경우 두 문자열을 비교하는 compare 함수를 정의해줬다.
파이썬 정렬 함수가 헷갈린다면 아래를 참고하여 공부해보자.
https://docs.python.org/ko/3/howto/sorting.html
Sorting Techniques
Author, Andrew Dalke and Raymond Hettinger,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted lis...
docs.python.org