https://school.programmers.co.kr/learn/courses/30/lessons/42576
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
이 문제의 풀이과정이 Counter를 이용하면 굉장히 간단해지는 걸 알고 Counter를 공부했다.
Counter
import collections
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
>>> Counter("hello world")
Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
>>> Counter('hello world').most_common()
[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
>>> Counter('hello world').most_common(1) # 인자 개수만큼 리턴
[('l', 3)]
counter 객체끼리 연산도 가능하다
>>> counter1 = Counter(["A", "A", "B"])
>>> counter2 = Counter(["A", "B", "B"])
>>> counter1 + counter2
Counter({'A': 3, 'B': 3})
>>> counter1 - counter2
Counter({'A': 1})
Reference
https://www.daleseo.com/python-collections-counter/
파이썬 collections 모듈의 Counter 사용법
Engineering Blog by Dale Seo
www.daleseo.com
'Python' 카테고리의 다른 글
2차원 리스트에서 최댓값, 최솟값 찾기 (1) | 2023.10.10 |
---|---|
[Python] 정규식을 이용한 패턴 찾기 (0) | 2023.02.14 |