티스토리 뷰

AI/CS

[CS] 알고리즘 - 정렬

brave_sol 2025. 3. 26. 15:02

1. open(0) : 표준 입력(stdin)

2. lines = [*open(0)] : 한 줄 씩 읽어서 리스트로 저장,

= input().splitlines()
3.언패킹*: 공백으로 구분된 형태로 출력

- print(*sorted_numbers)

lines = [*open(0)]
numbers = map(int, lines[1:])  # 첫 줄 제외하고 숫자만
sorted_numbers = sorted(numbers)
print(*sorted_numbers)

 

4. cmp_to_key

from functools import cmp_to_key

# cmp_to_key 내부 원리를 단순화한 예시
def cmp_to_key(mycmp):
    class K:
        def __init__(self, obj):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        # __le__, __ge__, __ne__ 등도 비슷하게 정의할 수 있음
    return K

# 원래 사용법 (functools에서 제공하는 cmp_to_key 사용)
# numbers를 문자열로 변환한 리스트
numbers = ["6", "10", "2"]
numbers.sort(key=cmp_to_key(compare))
print(numbers)  # 정렬 결과 예: ['6', '2', '10']

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함