[pro] 여행 경로

letsbebrave·2022년 6월 23일
0

codingtest

목록 보기
137/146

문제

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

풀이

answer = []

def processing(tickets):
    adj_port = dict()
    
    for a, b in tickets:
        if a in adj_port:
            if b in adj_port[a]:
                adj_port[a][b] += 1
            else:
                adj_port[a][b] = 1
        else:
            adj_port[a] = {b:1}
    return adj_port

def btracking(adj_port, now_port, total_t, used_t = 0, path = ['ICN']):
    if used_t == total_t:
        answer.append(path.copy())
        return
    else:
        if now_port in adj_port:
            for next_port, cnt in adj_port[now_port].items():
                if cnt:
                    path.append(next_port)
                    adj_port[now_port][next_port] -= 1
                    btracking(adj_port, next_port, total_t, used_t+1, path) # 지역변수는 매개변수로 + 1 (재귀 끝났을 때 원래 상태로 돌아옴)
                    adj_port[now_port][next_port] += 1
                    path.pop()

def solution(tickets):
    total_t = len(tickets)
    adj_port = processing(tickets)
    # adj_port {'ICN': {'SFO': 1, 'ATL': 1}, 'SFO': {'ATL': 1}, 'ATL': {'ICN': 1, 'SFO': 1}}
    btracking(adj_port, 'ICN', total_t)
    print(answer)
    answer.sort() 
    # 만일 가능한 경로가 2개 이상일 경우 알파벳 순서가 앞서는 경로를 return 
    # 여러 개의 answer 후보군 중 알파벳 순서가 앞서는 경로인 것 순으로 정렬
    # 그 내부에서 바꾸는 건 아님!!
    # 후보군의 순서를 알파벳 순으로 조정하는 것!!
    
    return answer[0]

디폴트 매개변수

파이썬 함수의 기본값 인자(default parameter)란 함수를 호출할 때 인자의 값을 설정하지 않아도 기본값이 할당되도록 하는 기능이다. 기본값은 함수를 정의할 때 지정해준다.

매개변수가 여러 개인 경우 뒤의 매개변수부터 디폴트 값을 가질 수 있다.

def print_hello(to1, to2='analysis'): 
    print('hello', to1, to2)

print_hello('data') #hello data analysis
print_hello('data', 'info') #hello data info

또 한 가지 주의할 점은 기본 인자는 최초의 호출 시에만 지정된 값으로 초기화 되고 이후의 호출에서는 그렇지 않다는 점이다. 따라서 리스트나 딕셔너리와 같은 가변(muatble) 객체를 기본 인자로 사용할 때 문제가 된다.

이 예제를 보면 기본 인자 L은 최초의 호출에서만 빈 리스트로 초기화 되고 그 이후의 호출에서는 그 내용물은 유지된다. 따라서 리스트의 요소가 축적되는 것이다. (마치 C/C++에서의 static 변수와 비슷한 동작을 수행한다.)


>>> def f(a, L=[]):
...     L.append(a)
...     return L
...
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

Ref.

https://wikidocs.net/85321
http://studymake.blogspot.com/2015/05/default-parameter.html

profile
그게, 할 수 있다고 믿어야 해

0개의 댓글