코딩테스트/programmers (python)

Programmers / 2단계 / 여행 경로 / python

seulll 2024. 5. 19. 00:02

 

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

 

 

코드

import collections

def solution(tickets):
    graph = collections.defaultdict(list)
    
    for a, b in sorted(tickets, key=lambda x: x[1]):
        graph[a].append(b)
    
    route = []

    def DFS(start):
        while graph[start]:
            DFS(graph[start].pop(0))
        route.append(start)
             

    DFS("ICN")
    return route[::-1]

 

defaultdict란?

없는 key에 접근할 경우 에러 처리를 위해 지정한 기본값으로 초기화한다.

dictionary와 동일하게 [key : value] 형식으로 구성된다. 모든 key에 대해 기본(default) 값을 설정해준다. 

 

from collections import defaultdict

dic = defaultdict(int) # 기본값 0을 가지는 정수
print(dic['apple'] # 키가 존재하지 않으므로 기본값 0 반환

 

 

참조

 

https://velog.io/@lgs03042/Python%EC%9D%98-defaultdict%EC%99%80-%EC%9D%BC%EB%B0%98-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-%EB%B9%84%EA%B5%90%ED%95%98%EA%B8%B0

 

Python의 defaultdict와 일반 딕셔너리 비교하기

Python에서 딕셔너리는 데이터를 저장하고 검색하는 데 자주 사용되는 유용한 자료 구조이다. Python은 표준 딕셔너리 {} 외에도 collections 모듈을 통해 defaultdict를 제공한다. 이 두 딕셔너리의 주된

velog.io

 

 

https://00h0.tistory.com/24

 

[Python] defaultdict란?

들어가며 파이썬에는 다양한 자료구조가 있다. list, set, dictionary 등등이 존재한다. 이번에는 dictionary와 비슷한 defaultdict에 대해서 알아볼 예정이다. defaultdict란? 우선 형태는 dictionary와 동일하게 [

00h0.tistory.com