Python

Python – 표준 모듈(collections편)

Counter

  • Counter 선언
from collections import Counter

counter_str = "45678987654345678987654"
counter = Counter(counter_str)
print(counter)
# Counter({'4': 4, '5': 4, '6': 4, '7': 4, '8': 4, '9': 2, '3': 1})
  • most_common(N) – 포함 문자 수 빈도순 상위 N개까지 출력 (오름차순 정렬)
print(my_counter.most_common(4))
# [('4', 4), ('5', 4), ('6', 4), ('7', 4)]
  • update(str) – 문자열 추가 후 리카운터
my_counter.update("634725173")
print(my_counter)
# Counter({'7': 6, '4': 5, '5': 5, '6': 5, '8': 4, '3': 3, '9': 2, '2': 1, '1': 1})

namedtuple

  • namedtuple 선언
from collections import namedtuple

Point = namedtuple("Hello", ['x','y','z'])
pt = Point(1,2,3)
print(pt)
# Hello(x=1, y=2, z=3)

OrderedDict

  • OrderedDict 선언
from collections import OrderedDict

ordered_dict = OrderedDict()
ordered_dict['a'] = 5
ordered_dict['b'] = 4
ordered_dict['c'] = 3
ordered_dict['d'] = 2
print(ordered_dict)

# OrderedDict([('a', 5), ('b', 4), ('c', 3), ('d', 2)])

# dictionary와 거의 비슷하다
ordered_dict = {}
ordered_dict['a'] = 5
ordered_dict['b'] = 4
ordered_dict['c'] = 3
ordered_dict['d'] = 2
print(ordered_dict)
# {'a': 5, 'b': 4, 'c': 3, 'd': 2}
  • move_to_end – 키 값을 받아 마지막으로 옮겨주는 기능 ( dictionary에는 없는 기능 )
ordered_dict.move_to_end('b')
# OrderedDict([('a', 5), ('c', 3), ('d', 2), ('b', 4)])

defaultdict

  • defaultdict 선언 – 타입을 지정하여 keyerror를 방지하고 타입에 따른 기본값을 받을수있음
from collections import defaultdict

default_dict = defaultdict(int)
print(default_dict["f"])
# 0

default_dict = defaultdict(float)
print(default_dict["f"])
# 0.0

default_dict = defaultdict(str)
print(default_dict["f"])
# 공백

deque ( 참고 – deque 알고리즘 )

  • append
deq.append(5)
# deque([5])

deq.appendleft(4)

# deque([4, 5])

deq.append(6)
# deque([4, 5, 6])
  • extend – 리스트 내용을 차례대로 deque에 저장 (내용을 순차적으로 저장하기때문에 extendleft의 경우 역순으로 저장)
deq.extend([7,8,9])
# deque([4, 5, 6, 7, 8, 9])

deq.extendleft([3,2,1])
# deque([1, 2, 3, 4, 5, 6, 7, 8, 9])
  • pop
deq.popleft()

# deque([2, 3, 4, 5, 6, 7, 8, 9])

deq.pop()
# deque([2, 3, 4, 5, 6, 7, 8])
  • remove – 지정 인자값 제거
deq.remove(3)
# deque([2, 4, 5, 6, 7, 8])
  • deque 활용해보기 – 백준 18258번 ( 참고 – deque 알고리즘 )
문제 (https://www.acmicpc.net/problem/18258)

정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 여섯 가지이다.

push X: 정수 X를 큐에 넣는 연산이다.
pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
size: 큐에 들어있는 정수의 개수를 출력한다.
empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
import sys
import collections
N = int(sys.stdin.readline())
deq = collections.deque()

for i in range(N):
    command = sys.stdin.readline().split()
    
    if command[0] == "push":
        deq.append(command[1])
    elif command[0] == "pop":
        if len(deq) == 0: print(-1)
        else: print(deq.popleft())
    elif command[0] == "empty":
        if len(deq) == 0: print(1)
        else: print(0)
    elif command[0] == "size": 
        print(len(deq))
    elif command[0] == "front":
        if len(deq) == 0: print(-1)
        else:
            temp_num = deq.popleft()
            deq.appendleft(temp_num)
            print(temp_num)
    elif command[0] == "back":
        if len(deq) == 0: print(-1)
        else:
            temp_num = deq.pop()
            deq.append(temp_num)
            print(temp_num)

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.