Notice
Recent Posts
Link
- Today
- Total
hye-log
[프로그래머스]K번째수(Python) 본문
0. 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/42748
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 설명
1) array 자르고 정렬하기
2) 정렬한 array에서 k번째수 찾기
2. 입출력
# input
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
# output
answer = [5, 6, 3]
3. 코드
1) 첫 번째 코드
def solution(array, commands):
answer = []
for c in range(len(commands)):
new_list = array[commands[c][0]-1:commands[c][1]] # 새로운 배열 만들기
new_list.sort()
answer.append(new_list[commands[c][2]-1]) # k번째 수 구하기
return answer
실행 결과
2) 두 번째 코드
def solution(array, commands):
answer = []
for c in range(len(commands)):
new_list = sorted(array[commands[c][0]-1:commands[c][1]]) # 새로운 배열 만들기
answer.append(new_list[commands[c][2]-1]) # k번째 수 구하기
return answer
실행 결과
4. 알게된 점
1) array.sort(), sorted(array)의 차이
sort는 현재 array에서 정렬 후 저장하고,
sorted는 현재 array를 복사해서 정렬함
현재의 배열 순서를 유지할 필요가 없으면 -> sort
현재의 배열 순서를 유지할 필요가 있으면 -> sorted
### sort
a = [2, 1, 3]
print('before sort >>', a) # [2, 1, 3]
a.sort()
print('after sort >>', a) # [1, 2, 3]
### sorted
a = [2, 1, 3]
print('before sort >>', a) # [2, 1, 3]
b = sorted(a)
print('after sort a >>', a) # [2, 1, 3]
print('after sort b >>', b) # [1, 2, 3]
5. Github
https://github.com/iihye/Algorithm/blob/main/Programmers/kth_number.py
GitHub - iihye/Algorithm
Contribute to iihye/Algorithm development by creating an account on GitHub.
github.com
728x90
'CodingTest > Programmers' 카테고리의 다른 글
[프로그래머스]오픈채팅방(Python) (0) | 2022.08.16 |
---|---|
[프로그래머스]문자열 압축(Python) (0) | 2022.08.12 |
[프로그래머스]완주하지 못한 선수(Python) (0) | 2022.08.10 |
[프로그래머스]폰켓몬(Python) (0) | 2022.08.09 |
[프로그래머스]소수 만들기(Python) (0) | 2022.08.09 |
Comments