[algo] 코딩테스트 고득점 kit

letsbebrave·2022년 6월 4일
0

algorithm

목록 보기
16/16

기간

22년 05월 23일 ~ 약 한달 간

목표

코딩테스트 고득점 kit 문제 다 풀기

  • 풀이 다 이해하고 쓸 수 있을 정도로 익히기

해시

완주하지 못한 선수

collections.Counter를 이용한 카운팅

["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})

collections.Counter를 이용한 연산

또한, 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})

most_common() 함수 - 최빈값 구하기

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-완주하지-못한-선수

소수 찾기

집합

  • 중복을 허용 X
  • 순서가 X (unordered)

.add( ) - 집합에 원소 추가하기

>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}

.update( ) - 집합에 값 여러 개 추가하기

>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}

.remove( ) - 특정 값 제거하기

>>> 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}
profile
그게, 할 수 있다고 믿어야 해

0개의 댓글