[프로그래머스] 정수 내림차순으로 배치하기

2024. 5. 27. 15:42개인활동/코테

def solution(n):
    answer = ""
    num_list = sorted(str(n), reverse=True)
    for i in num_list:
        answer += i
    return int(answer)

 

정렬까지는 짧게 했지만... 리스트로 변환되었을 때 이를 효율적으로 쌓고 출력하는 방식이 무엇일지 고민이 많았다.

결국에는 for문을 이용해 차곡차곡 더해주는 방식을 선택했는데, 다른 사람의 코드를 보고 감탄하였다.

 

def solution(n):
    ls = list(str(n))
    ls.sort(reverse = True)
    return int("".join(ls))

 

바로 join을 이용한 것인데, 이는 python 내장 함수로 join의 파라미터로 iterable 객체가 들어간다.

 

print("".join(["1", "4", "5", "0"]))
>>> 1450

 

예시로 이런 코드를 돌렸을 때 다음과 같은 결과를 보인다.

이 내장함수는 iterable 객체를 받아 문자열로 차곡차곡 쌓아서 전달해주는 함수로, 우리가 풀고자 하는 부분을 빠르게 해결해줄 수 있다.

 

또 문제를 쉽게 해결할 수 있는 함수를 알아가며....

 

https://docs.python.org/3/library/stdtypes.html#str.join

 

Built-in Types

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...

docs.python.org