Algorithm

[프로그래머스] Level1 | 달리기 경주 - 파이썬(Python) | 연습문제

토오오끼 2024. 3. 28. 01:18
728x90
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/178871

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


제출한 코드

def solution(players, callings):
    answer = []
    
    for i in range(len(callings)):
        call_score = players.index(callings[i])
        players.pop(call_score)

        new_score = call_score-1
        
        players.insert(new_score, callings[i])
    
    answer = players
    
    return answer

단순하게 list에서 해당 index를 pop 해 오고 당겨진 위치에 insert를 하면 될 것 같아서 구현을 했고 실행 시 에러 없이 무사히 실행이 되었다.

하지만 채점을 누르니

우당탕탕 시간 초과로 실패했다.. index 함수 자체가 list를 계속 돌면서 값의 위치를 찾기 때문에 list의 길이가 길어지면 시간이 초과되는 것 같았다.

 

수정한 코드 - 정답

def solution(players, callings):
    answer = []
    
    race = {key: i for i, key in enumerate(players)}
    print(race)

    for call in callings:
        score = race[call]
        race[call] -= 1
        
        race[players[score-1]] += 1
        players[score-1], players[score]  = players[score], players[score-1]
    
    print(players)

    answer = players
    
    return answer

원래 처음부터 딕셔너리로 풀어보려고 했으나 이상하게 잘 안됐는데 pop-insert를 생각 해 낸 뒤라 그런지 이전보다 간단하게 풀 수 있었다.

.index를 사용했던 부분을 players와 players의 index를 딕셔너리로 미리 만들어 두고 callings를 for문 돌리면서 call 된 선수의 기존 등수를 딕셔너리에서 빼 오는 걸로 대체 했다.

그리고 players에서 바로 앞 선수와 위치를 바꿔치기를 해 줬다.

 

.index가 시간을 엄청 잡아 먹는 다는 걸 처음 알게 되었다..!

 


https://github.com/YOOHYOJEONG/algorithm_practice/blob/master/programmers/Level01_practice/%EB%8B%AC%EB%A6%AC%EA%B8%B0%EA%B2%BD%EC%A3%BC.py

 

algorithm_practice/programmers/Level01_practice/달리기경주.py at master · YOOHYOJEONG/algorithm_practice

알고리즘 공부 및 코딩테스트 준비. Contribute to YOOHYOJEONG/algorithm_practice development by creating an account on GitHub.

github.com

 

728x90
반응형