본문 바로가기

CodingTest/Programmers

[ 프로그래머스 ] K번째 수

 

/  1번째 제출  /
def solution(array, commands):
    answer = []
    for command in commands:
        i, j, k = command
        new = array[i-1:j]
        new.sort()
        answer.append(new[k-1])
    return answer

 

채점 결과
정확성: 100.0
합계: 100.0 / 100.0
 
생각보다 간단하게 구현했습니다.
 
다른 분들의 풀이를 보면 sort() 보다는 sorted()를 훨씬 많이 쓰시는 것을 보고 두 메서드 간 차이가 있는지 궁금해졌습니다. 저는 보통 sort()를 더 자주 사용하기 때문입니다.
더보기

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.
  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.
  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

 

진짜 명확한 차이가 있었는데 이걸 모르면서 사용했다니 부끄럽습니다. 기본 개념도 없이 무작정 쓰는 사람이었다니..

 

이 문제에서는 이 차이점을 이용해 1번째 제출과 다른 구현이 가능한 것을 실험하고 확인했습니다.

 

 

/  2번째 제출  /

def solution(array, commands):
    answer = []
    for command in commands:
        i, j, k = command
        answer.append(sorted(array[i-1:j])[k-1])
    return answer

sorted를 사용하면 새로 정렬된 배열을 리턴하기 때문에 같은 줄에서 곧바로 인덱스로 접근해서 사용할 수 있습니다.

따라서 한 줄로 간편하게 표현이 가능합니다.

하지만 sort는 in-place 연산을 하되 아무것도 리턴하지 않습니다. 따라서 곧바로 sort()값에 인덱스로 접근이 불가능합니다. list를 리턴하는 것이 아니라 None Type이기 때문입니다.

 


/  다른 분들 풀이  /

 

1) 

정말 간단하게 구현한 분이 있었습니다. 와 멋지다 생각을 했습니다.물론 간단하게 푸는 것만이 능사는 아니지만 익혀 둔다면 필요한 곳에 응용할 수 있겠다 싶어서 검토합니다.

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

list(), map(), lambda 를 섞어서 구현하는건 저번 문제에서 복기하고 넘어간 방식입니다.

와.. 근데 이걸 이렇게 사용하다니! for문 대신 map()함수를 이용하고, sort부분을 lambda식을 사용해 함수처럼 이용한 풀이입니다. 

 

2) 

def solution(array, commands):
    return [sorted(array[a-1:b])[c-1] for a,b,c in commands]

마찬가지로 한 줄로 구현했는데 이건 리스트 컴프리헨션을 이용한 풀이입니다.

리스트 컴프리헨션을 사용하긴 하지만 아직 익숙하지는 않은데 " for 요소 in 리스트 " 요런 식의 이용이 낯설었는데 덕분에 사용법을 또 익히고 갑니다.

 

list comprehension

A compact way to process all or part of the elements in a sequence and return a list with the results. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. The if clause is optional. If omitted, all elements in range(256) are processed.

from https://docs.python.org/3/glossary.html#term-list-comprehension

'CodingTest > Programmers' 카테고리의 다른 글

[ 프로그래머스 ] H-index  (0) 2022.06.21
[ 프로그래머스 ] 가장 큰 수  (0) 2022.06.21
[ 프로그래머스 ] 더 맵게  (0) 2022.06.20
[ 프로그래머스 ] 프린터  (0) 2022.06.20
[ 프로그래머스 ] 기능개발  (0) 2022.06.20