상세 컨텐츠

본문 제목

[python]dict? 해시?

공부

by 근성 2023. 3. 30. 17:23

본문

해시 알고리즘을 요구하는 문제는 파이썬에서는 dict형식으로 해결하는 경우가 많습니다.

 

dict형식을 통해서 아래 링크의 문제를 해결했습니다만, C를 사용하다가 Python을 사용해서 dict에 관련된 method숙지가 미숙했습니다.

1. 두개의 value가 있는 list(a, b)를 b에 관한 dict로 설정

2. b의 value를 가진 list들을 만날때마다 index 증가

[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]

    clothes_type = {} # dict형 변수 선언
    
    for name, kind in clothes:
        if kind not in clothes_type: # b의 value가 dict에 없으면 index 2증가
            clothes_type[kind] = 2
        else:
            clothes_type[kind] = clothes_type[kind] + 1

 

 

3. dict의 value를 사용하기

    for num in clothes_type.values():
        answer = answer * num

dict형 변수의 이름의 method에는 values()라는 method가 존재해서, 해당 method를 반복문을 통해서 연산

관련글 더보기

댓글 영역