알고리즘

프로그래머스 [Python] - 가장 큰 수

BKM 2024. 6. 14. 00:01

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42746

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이1

def solution(numbers):
    numbers = list(map(str, numbers))
    numbers.sort(key=lambda x: x*3, reverse=True)
    return str(int(''.join(numbers)))

제한사항에 1000이하의 수만 존재한다고 되어있었기 때문에 가능한 풀이

개인적인 생각으로는 sustainable하지 못한 코드라고 생각한다.(제한사항이 없는 경우는 적용할 수 없음)

풀이2

import functools

def comparator(a,b):
    t1 = a+b
    t2 = b+a
    return (int(t1) > int(t2)) - (int(t1) < int(t2)) #  t1이 크다면 1  // t2가 크다면 -1  //  같으면 0

def solution(numbers):
    n = [str(x) for x in numbers]
    n = sorted(n, key=functools.cmp_to_key(comparator),reverse=True)
    answer = str(int(''.join(n)))
    return answer

개인적으로 가장 이상적이고 내가 구현하고자 했던 방향의 코드

'cmp_to_key'함수를 해당 코드를 통해 알게 되었다.

functools.cmp_to_key

'compare to key'의 약어로, source code는 다음과 같다

def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        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
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        __hash__ = None
    return K

 

 

sorted 함수에서 cmp_to_key가 사용되는 작동 원리는 다음과 같다.

def compare(a,b):
	return (a>b)-(b>a) # a>b : 1 / a<b : -1 / a==b : 0
  1. 어떠한 함수 compare가 있다고 할때, cmp_to_key 함수를 사용해 이를 sorted 함수의 key인자로 활용할 수 있도록 변환해준다.
    이렇게 되면, key_function은 호출될때 K라는 class를 반환하는 함수의 역할을 하게 된다.
  2. sorted 함수의 key인자로 key_function을 넣어준다.
  3. sorted 함수가 실행되면 list의 각 element가 key_function의 인자로 들어가 각각의 instance를 생성하게 된다.
  4. 작은지 혹은 큰지 여부를 확인할 떄, 각 instance내의 method를 활용해 True/False를 반환하고, 이를 활용해 순서를 정렬한다.