Search: 10816 [defaultdict]

SeongGyun Hong·2025년 1월 1일

Python

목록 보기
10/34

백준 10816번 문제 풀이 중 defaultdict을 활용하게 되어 이에 관해 정리함

  • int()는 아무것도 없으면 기본값으로 0을 반환

  • 그래서 defaultdict(int) 이렇게 쓰면, 키가 없을 때 자동으로 int() 호출해서 기본값 0을 넣어줌.

  • 근데 int(0)은 이미 0이라는 값임. 이건 함수가 아니라 숫자 값이라 callable이 아님.

  • defaultdict는 "기본값 생성기"가 필요한데, 숫자 값을 넘기면 안 됨.

    현재 Type Error 난 걸 보면 아래와 같음

    num_dict = defaultdict(int(0))
    TypeError: first argument must be callable or None

    왜 에러가 났는고 보면 callable한 객체를 안넣어줘서 그럼..!

  • 결과적으로 defaultdict(int(0))처럼 쓰면 TypeError 터지는 거고, defaultdict(int) 이렇게 해야 정상 작동함.

    from collections import defaultdict
    
    # 기본값 0 세팅
    num_dict = defaultdict(int)
    
    # 키가 없으면 자동으로 0 반환
    print(num_dict["key"])  # 0 출력
    
    # 값 추가
    num_dict["key"] += 1
    print(num_dict["key"])  # 1 출력

요약

  • int는 함수라 기본값 0 반환 가능.
  • int(0)은 그냥 숫자라 callable 안 됨.
  • defaultdict 기본값 설정할 땐 항상 함수 넣기. (defaultdict(int) 이런 식으로.)
profile
헤매는 만큼 자기 땅이다.

0개의 댓글