포포's 코딩&일상 기록

7월 6일 코테 본문

코테

7월 6일 코테

포포252 2023. 7. 6. 19:51

7월 6일 목요일 코테

- 달리기 경주 문제 : 코딩테스트 연습 - 달리기 경주 | 프로그래머스 스쿨 (programmers.co.kr)

 

프로그래머스

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

programmers.co.kr

 

처음짠 코드 

def solution(players, callings):
    #answer = []

    for name in callings:# callings 에서 이름을 하나씩 가져온다
        i = players.index(name) #해당이름의 인덱스 넘버를 찾는다 
        players[i],players[i-1] = players[i-1],players[i] #위치 교체

    #answer =players # 복사
    return players

 

 

로 짰는데 시간초과 걸림

gpt 랑 bard 한테 물어봤는데 gpt 답이 내수준에선 좀더 나은듯

 

 

새로 알게된것

 

 

name_index = {name: index for index, name in enumerate(players)}

 

은 딕셔너리 컴프리헨션(Dict Comprehension)을 사용한 코드입니다.

 

 

이 코드는 players 리스트의 각 요소에 대해 인덱스를 키(key)로, 요소를 값(value)로 가지는 딕셔너리를 생성합니다.

 

 

컴프리헨션은 간단히 말해 반복문과 조건문을 사용하여 컬렉션(리스트, 딕셔너리 등)을 생성하는 방법입니다.

 

 

{name: index for index, name in enumerate(players)}에서

 

enumerate(players)

 

players 리스트의 요소를 (인덱스, 요소) 쌍으로 반환하는 이터레이터를 생성합니다.

 

 

이렇게 생성된 (인덱스, 요소) 쌍을 for index, name in enumerate(players)에서 index와 name에 각각 할당합니다.

 

 

그리고 name: index는 딕셔너리의 키-값 쌍을 나타냅니다.

 

따라서 name_index 딕셔너리는 players 리스트의 요소를 키로, 해당 요소의 인덱스를 값으로 가지게 됩니다.

 

예를 들어, players 리스트가 ['mumu', 'soe', 'poe']인 경우, enumerate(players)는 다음과 같은 이터레이터를 반환합니다:

 

(0, 'mumu')
(1, 'soe')
(2, 'poe')

 

따라서 name_index 딕셔너리는 {'mumu': 0, 'soe': 1, 'poe': 2}가 됩니다.

 

이렇게 생성된 딕셔너리는 name을 키로 사용하여 해당 이름의 인덱스를 빠르게 찾을 수 있게 해줍니다.

 

 

 

수정된 코드 

def solution(players, callings):

    player_index = {name:index for index, name in enumerate(players)}
    for name in callings:# callings 에서 이름을 하나씩 가져온다
        i = player_index[name] #해당이름의 인덱스 넘버를 찾는다
        name2 = players[i-1] # 뒤로간애 이름 찾기
        players[i],players[i-1] = players[i-1],players[i] #위치 교체
    
        player_index[name] = player_index[name] -1  # index 값 변경 
        player_index[name2] = player_index[name] +1 
        

    return players

 

'코테' 카테고리의 다른 글

7월 10일 코테  (0) 2023.07.16
7월 9일 코테  (0) 2023.07.16
7월 8일 코테  (0) 2023.07.16
7월 15일 코테  (0) 2023.07.16
7월 7일 코테  (0) 2023.07.07