programmers- lv.1 (달리기 경주)

이예송·2023년 7월 20일

PS

목록 보기
52/97

문제링크: 달리기 경주

✍🏻 Information

content
언어python
난이도⭐️⭐️+(0.5)
풀이시간30분
제출횟수
인터넷검색유무yes




🍒 My Code

def solution(players, callings):
    _players={}
    for idx, player in enumerate(players):
        _players[player]=idx
    for calling in callings:
        #idx = players.index(calling)
        idx = _players[calling]
        _players[players[idx-1]], _players[players[idx]]= _players[players[idx]],_players[players[idx-1]]
        players[idx], players[idx-1]= players[idx-1],players[idx]
    return players




💡 What I learned

  • 검색한 내용: list_name.index(찾고싶은내용)
  • 중복되는 원소들의 인덱스 모두 찾고 싶을때는 numpy.where 사용
  • 처음에는 index함수로 찾았는데 얘가 생각보다 시간을 엄~청 잡아먹어서 dictionary에 순위를 저장해두고 써먹었다. (함수 호출이 이렇게까지 시간이 많이 들다니)
  • 내 예전 풀이는 아래와 같은데 이런식으로 풀면 players = ["mumu", "soe", "poe", "kai", "mine"], callings = ["mine", "kai", "mine", "kai"]과 같은 상황일때 문제가 생긴다. 이런 경우를 처리하려고 해보았는데 쉽지 않아서 순위를 저장해두고 하나하나 역전을 처리하는게 낫겠다 싶었다.
def solution(players, callings):
    answer = players
    times = []
    for player in players:
        times.append(callings.count(player))    
    for idx in range (len(players)):
        answer[idx],answer[idx-times[idx]]=answer[idx-times[idx]],answer[idx]      
    return answer

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

뛰어난 글이네요, 감사합니다.

답글 달기