[just-stopyoon] programmers_가장 큰 수_Python - #32
Open
just-stopyoon wants to merge 1 commit into
Open
Conversation
just-stopyoon
requested review from
jaejunmin408,
mingxoxo,
sangkyu39 and
seungbinpark
February 2, 2025 08:40
mingxoxo
approved these changes
Feb 8, 2025
mingxoxo
left a comment
Member
There was a problem hiding this comment.
저도 이번에 이 문제를 풀면서 cmp_to_key()를 처음 알게 되었는데 신기하더라구요!
잘 쓰면 정렬 문제에서 유용하게 잘 쓸 것 같습니다 ㅎㅎ
GPT한테 물어봤을 때 이 방법말고 다른 방법도 제안해줬던 것 같은데 기회되면 또 보아야겠어요..!
수고하셨습니다 ~~
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🔗 문제 링크
📰 문제 요약
문제 설명
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내기
입력
정수가 담긴 배열 numbers
출력
정답이 너무 클 수 있으니 문자열로 바꾸어 return
🔓 문제 접근 방식
기본 아이디어
사용 알고리즘
💻 구현 방법
1. 기본 아이디어
정수를 조합하여 가장 큰 수를 만들기 위해서는 숫자의 순서를 적절히 배치하는 것이 중요
숫자를 이어 붙일 때 큰 값이 나오도록 정렬해야하기 때문에 두 숫자를 이어 붙였을 때 더 큰 수가 만들어지는 순서대로 정렬
2. 정렬 기준 정의
기본적인 숫자 크기 비교가 아니라, 두 숫자를 이어 붙였을 때 더 큰 값이 되도록 비교해야 하기 때문에 커스텀 비교 함수를 정의
두 숫자
x,y를 비교하는 방법:x + y와y + x를 비교x = "3",y = "30"이면:"330"(x가 앞) vs"303"(y가 앞)"330"이 더 크므로x가 앞에 와야 함.x + y > y + x이면x가 앞,x + y < y + x이면y가 앞에 오도록 설정.👍🏻 최종 제출 코드
📝 새로 학습한 내용
이런 유형이 처음 나와서 굉장히 막막했는데, 굉장히 고전적인 풀이가 있었다!
구현 방식을 간단하게 정리하면,
✅ 숫자를 문자열로 변환한 후, 이어 붙였을 때 더 큰 값을 기준으로 정렬한다.
✅ 정렬 기준:
(x+y) > (y+x)를 비교하여 내림차순 정렬을 수행한다.✅ 모든 숫자가
0일 경우"0"을 반환하는 예외 처리가 필요하다.해당 방식을 통해, 숫자를 문자로 변환한 것을 비교하는 방식으로 구현할 수 있었다.
cmp_to_keys
cmp_to_key는 사용자 정의 비교 함수를sort()에서 사용할 수 있도록 변환해준다.sort()는 기본적으로 비교 연산자<만 지원하는데,<,>를 다루기 때문에 중요하다.📚 참고 자료
[https://velog.io/@heyday_7/python-조건-정렬-하기-cmptokey](https://velog.io/@heyday_7/python-%EC%A1%B0%EA%B1%B4-%EC%A0%95%EB%A0%AC-%ED%95%98%EA%B8%B0-cmptokey)