프로그래머스_K번째 수_python

2021. 8. 4. 00:21코딩테스트

반응형

https://programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

def solution(array, commands):
    answer = []
    for c in commands:
        tmp = sorted(array[c[0]-1:c[1]])
        answer.append(tmp[c[2]-1])
    return answer

[내코드]

먼저 i,j대로 배열을 자르고, 정렬후에 해당 인덱스값을 반환.

 

 

def solution(array, commands):
    return list(map(lambda x:sorted(array[x[0]-1:x[1]])[x[2]-1], commands))

[다른사람코드]

람다를 써서 코드가 간결해짐.

list(map(함수, 리스트))

 

a = [1.2, 2.5, 3.7, 4.6]

 

1. 기존 형식

for i in range(len(a)):

    a[i] = int(a[i])

2. 람다

a = list(map(int, a))

 

print(a) // [1, 2, 3, 4]

반응형