일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 그래프 이론
- JavaScript
- 자바스크립트
- 다이나믹 프로그래밍
- 딕셔너리
- BASIC
- 너비 우선 탐색
- 파이썬
- 자료구조
- programmers
- CSS
- 프로그래머스
- DP
- 웹 프론트엔드
- 그래프이론
- web
- 알고리즘
- DFS
- lv2
- BFS
- 문자열
- 브루트포스 알고리즘
- 구현
- 그래프 탐색
- 그리디 알고리즘
- 정렬
- 백준
- level2
- 프로그래머스스쿨
- 스택
Archives
- Today
- Total
DevLog:-)
[프로그래머스][파이썬] 달리기 경주 본문
반응형

문제


코드
def solution(players, callings):
idx = {i: player for i ,player in enumerate(players)}
p = {player:i for i, player in enumerate(players)}
for call in callings:
loc = p[call] #호명한 선수의 등수
loc2 = loc-1 #앞 선수 등수
idx[loc] = idx[loc2] #선수:앞 선수 뒤로 보내기
idx[loc2] = call #선수:호명된 선수 앞으로 보내기
p[idx[loc]] = loc #등수:앞 선수 등수 낮추기
p[call] = loc2 #등수:호명된 선수 등수 올리기
return list(idx.values())
리스트에서 호명된 선수의 위치와 앞 선수의 위치를 바꿔야하는 문제이다.
(등수와 선수이름) 이 두 데이터에 쉽고 빠르게 접근할 수 있도록 두 개의 딕셔너리를 이용하여 풀었다!
딕셔너리 -> {index:player} , {player:index}
#추가코드
#1번
def solution(players, callings):
pla_dic = {key: i for i, key in enumerate(players)}
for p in callings:
c = pla_dic[p]
pla_dic[p] -= 1
pla_dic[players[c-1]] += 1
players[c-1], players[c] = players[c], players[c-1]
return players
1번 코드와 같이 딕셔너리 하나만으로도 풀이가 가능하다.
#2번
def solution(players, callings):
for call in callings:
if call in players:
x = players.index(call)-1
y = players.index(call)
players[x], players[y] = players[y], players[x]
return players
for문을 이용한 코드로도 정답을 도출할 수 있지만 시간초과가 발생한다!
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][Javascript]숫자 변환하기 (0) | 2023.07.21 |
---|---|
[프로그래머스][Javascript]땅따먹기 (0) | 2023.07.20 |
[프로그래머스][JavaScript]연속 부분 수열 합의 개수 (0) | 2023.07.19 |
[프로그래머스][JavaScript]최솟값 만들기 (0) | 2023.07.19 |
[프로그래머스][파이썬]추억점수 (0) | 2023.06.15 |