눈송이의 개발생활
[Programmers Lv.1]K번째수 (Python) 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/42748
내 코드
def solution(array, commands):
answer = []
for index in range(len(commands)):
temp = []
i = commands[index][0] - 1
j = commands[index][1]
k = commands[index][2] - 1
temp = array[i:j]
temp.sort()
answer.append(temp[k])
return answer
다른 사람 풀이
def solution(array, commands):
answer = []
for command in commands:
i,j,k = command
answer.append(list(sorted(array[i-1:j]))[k-1])
return answer
해결 방법
문제를 보자마자 바로 풀고 맞았다.
Python을 sort 함수가 있어서 이런 종류의 정렬 문제를 쉽게 풀 수 있는 것 같다.
코드를 더 "파이썬스럽게" 쓰지 못해서 매우 아쉽다...
중첩문과 다양한 종류의 for문을 더 다양하게 쓰는 연습이 아직 필요하다.
✅ list[start : end : step] : list slicing하는 방법 (list 이외의 set, tuple, 문자열에도 사용 가능)
start : 시작하는 index
end : 슬라이씽 끝내는 위치. (인덱스가 end인 원소는 포함 ❌)
step : 몇 개씩 가져올지 + 방향 (option)
➖ : 거꾸로 뒤에서부터 가져오기
➕ : 앞에서부터 가져오기
'Algorithm > Programmers' 카테고리의 다른 글
[Programmers Lv.1]완주하지 못한 선수 (Python) (0) | 2022.04.08 |
---|---|
[Programmers Lv.1]모의고사 (Python) (0) | 2022.04.06 |
[Programmers Lv.1]체육복 (Python) (0) | 2022.04.04 |
[Programmers Lv.1]다트 게임 (Python) (0) | 2022.04.04 |
[Programmers Lv.1]로또의 최고 순위와 최저 순위(Python) (0) | 2022.03.29 |
Comments