코테 공부/프로그래머스
[Python] 정렬/k번째 수
prefer_all
2021. 8. 6. 20:44
문제:
배열 array를 2차원 배열 commands를 기준으로 i번째 숫자부터 j번째 숫자까지 자르고 정렬한 후, k번째 수를 구하려고 함
* 1번째 수는 array[0]임
* TypeError: 'int' object is not iterable 오류/ int 값은 쪼갤 수 없는 단일 객체이기 때문에, 문자열, 튜플, 딕셔너리와 다르게 iterable하지 않다.
내 답안:
def solution(array, commands):
for i in range(0,len(array)): #숫자열 list -> 문자열 list(iterable하게 하기 위함)
array[i] = str(array[i])
temp = []
answer = []
for i in range(len(commands)):
if commands[i][0] == commands[i][1]:
temp = array[commands[i][0]-1]
else:
temp = array[commands[i][0]-1: commands[i][1]]
temp = list(map(int, temp)) #문자열 list -> 숫자열 list(sort하기 위함)
temp.sort()
temp = list(map(str, temp)) #숫자열 list -> 문자열 list(i번째 위치의 값 구하기 위함)
index = commands[i][2]-1
answer.append(temp[index])
answer = list(map(int, answer)) #문자열 list -> 숫자열 list(return하기 위함)
return answer
* map은 리스트의 요소를 지정된 함수로 처리해주는 함수 / list(map(함수, 리스트))
list(map(int, temp) : 문자열 list인 temp의 각 요소를 int로
list(map(str, temp) : 숫자열 list인 temp의 각 요소를 string으로
* append() 함수는 list에 요소를 추가할 때 사용
추가 공부
* sort() 함수와 sorted() 차이
>> list = [8,1,3]
>> print(list)
>> sort_list = list.sort()
>> print(sort_list)
...
...
[1,3,8]
None
sort() 함수의 return 값은 None. 원본 list 값이 정렬됨.
그에 비해, sorted() 함수 사용 시 원본 list 값은 유지하고 새 리스트에서 정렬됨.
>> list = [8,1,3]
>> sorted_list = sorted(list)
>> print(list)
>> print(sorted_list)
...
...
[8,1,3]
[1,3,8]
다른 풀이
def solution(array, commands):
answer = []
for command in commands: #commands에 있는 command(i, j, k)를 뽑는다.
i, j, k = command[0], command[1], command[2]
slice = array[i-1:j] # array에서 슬라이스를 하고
slice.sort() # 정렬하고
answer.append(slice[k-1]) # 인덱싱하자
return answer
#출처: https://jeongchul.tistory.com/640 [Jeongchul]
def solution(array, commands):
answer = []
for i in range(len(commands)):
arr_list = array[commands[i][0]-1:commands[i][1]]
arr_list.sort()
answer.append(arr_list[commands[i][2]-1])
return answer
#출처: https://jokerldg.github.io/algorithm/2021/03/31/k-number.html
def solution(array, commands):
return list(map(lambda x:sorted(array[x[0]-1:x[1]])[x[2]-1], commands))
commands가 [2,5,3]
[4,4,1]
[1,7,3] 이렇게 들어감