22년 05월 23일 ~ 약 한달 간
코딩테스트 고득점 kit 문제 다 풀기
["mislav", "stanko", "mislav", "ana"]
와 같은 배열이 주어질 경우, 사람마다 개수를 세고 싶을 때, from collections import Counter
의 Counter를 이용해서 딕셔너리 형태로 수를 세어 줄 수 있다.
import collections
b = [1,3,4,2,3,5,2,3,9]
a = [1,2,3,4,1,5,3,1,3,4,2,3]
print(collections.Counter(a) , collections.Counter(b))
# 출력 결과
# Counter({3: 4, 1: 3, 2: 2, 4: 2, 5: 1}) Counter({3: 3, 2: 2, 1: 1, 4: 1, 5: 1, 9: 1})
또한, counter 함수로 구한 딕셔너리의 값(value)끼리 연산이 된다. 연산은 + , - , &(교집합), |(합집합) 네가지가 가능하다.
import collections
b = [1,1,1,1,1,1]
a = [1,1,2,2,2,2]
print(collections.Counter(a) - collections.Counter(b))
print(collections.Counter(a) + collections.Counter(b))
# 출력 결과
# Counter({2: 4})
# Counter({1: 8, 2: 4})
collections.Counter(a).most_common(n)
a의 요소를 세어, 최빈값 n개를 반환. (리스트에 담긴 튜플형태로)
import collections
a = [1,1,1,2,3,2,3,245,9]
print(collections.Counter(a).most_common(3))
# [(1, 3), (2, 2), (3, 2)]
https://velog.io/@letsbebrave/pro-완주하지-못한-선수
>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}
>>> s1 = set([1, 2, 3])
>>> s1.remove(2)
>>> s1
{1, 3}
>>> s1 = set([1, 2, 3, 4, 5, 6])
>>> s2 = set([4, 5, 6, 7, 8, 9])
위와 같은 set 자료형이 있을 때,
>>> s1 & s2
{4, 5, 6}
4, 5, 6처럼 중복해서 포함된 값은 한 개씩만 표현됨
>>> s1 | s2
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s1 - s2
{1, 2, 3}
>>> s2 - s1
{8, 9, 7}