https://school.programmers.co.kr/learn/courses/30/lessons/178871?language=python3
프로그래머스
players = ["mumu", "soe", "poe", "kai", "mine"]
callings = ["kai", "kai", "mine", "mine"]
result = ["mumu", "kai", "mine", "soe", "poe"]
def solution(p, callings):
for name in callings:
# 선수의 현재 위치 찾기
index = p.index(name)
# 선수 위치 바꾸기
p[index], p[index - 1] = p[index - 1], p[index]
return p
위의 코드는 이상이 없어보인다.
하지만 시간 효율에서 에러가 발생한다.
def solution_two(p, callings):
# 선수 이름을 key로 하고 그 인덱스를 value로 하는 딕셔너리 생성
p_indices = {player: idx for idx, player in enumerate(p)}
# {
# "mumu": 0,
# "soe": 1,
# "poe": 2,
# "kai": 3,
# "mine": 4
# }
for calling in callings:
# 선수의 현재 위치 찾기
idx = p_indices[calling] # 키값으로 인덱스 value 를 찾는다.
# 위치를 바꾸기 전에 딕셔너리를 업데이트
p_indices[p[idx - 1]] = idx
# player_indices 딕셔너리를 사용해 현재 calling 이름을 가진 선수의 위치 (인덱스)를 찾습니다.
p_indices[calling] = idx - 1
# 선수의 위치 바꾸기
p[idx], p[idx - 1] = p[idx - 1], p[idx]
# {
# "mumu": 0,
# "soe": 1,
# "kai": 2,
# "poe": 3,
# "mine": 4
# }
return p