본문 바로가기
👩‍💻 Programming/Coding Test 문제 풀이

[Baekjoon] 10845 큐(파이썬 python)

by codingBear 2022. 12. 23.
728x90
반응형

이번 문제는 아래 링크에서 풀어볼 수 있습니다.

 

10845번: 큐

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net


문제

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

명령은 총 여섯 가지이다.

  • push X: 정수 X를 큐에 넣는 연산이다.
  • pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 큐에 들어있는 정수의 개수를 출력한다.
  • empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
  • front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.

예제 입력 1

15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front

예제 출력 1

1
2
2
0
1
2
-1
0
1
-1
0
3

 


정답 코드

나의 풀이
 파이썬 Ver.
from collections import deque
import sys

n = int(sys.stdin.readline().rstrip())


def mySolution(n):
    def push(num):
        queue.append(num)

    def pop():
        return queue.popleft() if queue else -1

    def size():
        return len(queue)

    def empty():
        return 1 if not queue else 0

    def front():
        return queue[0] if queue else -1

    def back():
        return queue[-1] if queue else -1

    queue = deque()

    for _ in range(n):
        data = sys.stdin.readline().rstrip().split()
        oper = data[0]

        if oper == "push":
            push(data[1])
        elif oper == "pop":
            print(pop())
        elif oper == "size":
            print(size())
        elif oper == "empty":
            print(empty())
        elif oper == "front":
            print(front())
        elif oper == "back":
            print(back())


mySolution(n)


자바스크립트/NodeJS Ver.

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let [n, ...input] = fs.readFileSync(filePath).toString().trim().split('\n');

n = parseInt(n);
const data = input.map((val) => val.split(' '));

const solution1 = (data) => {
    const push = (num) => queue.push(num);
    const pop = () => queue.shift() || -1;
    const size = () => queue.length;
    const empty = () => (queue.length ? 0 : 1);
    const front = () => queue[0] || -1;
    const back = () => queue[queue.length - 1] || -1;

    const queue = [];
    let result = '';

    for (let i of data) {
        const oper = i[0];

        switch (oper) {
            case 'push':
                push(i[1]);
                break;
            case 'pop':
                result += pop() + '\n';
                break;
            case 'size':
                result += size() + '\n';
                break;
            case 'empty':
                result += empty() + '\n';
                break;
            case 'front':
                result += front() + '\n';
                break;
            case 'back':
                result += back() + '\n';
                break;
        }
    }

    return result.trim();
};

console.log('solution1');
console.log(solution1(data));

 


문제 풀이

 파이썬 모듈 collections의 deque를 활용하여 풀었다. 들어오는 입력값에 맞춰 append, popleft 등 deque가 제공하는 메서드를 적절하게 활용하여 풀면 된다. 큐는 FIFO(First In First Out) 구조란 점을 염두에 두고 풀자.

 스택을 구현한 이 문제와 비슷하다.


함께 보기

https://docs.python.org/3.8/library/collections.html#collections.deque

 

collections — Container datatypes — Python 3.8.14 documentation

collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f

docs.python.org

https://docs.python.org/ko/3.7/library/queue.html

 

queue — 동기화된 큐 클래스 — Python 3.7.14 문서

queue — 동기화된 큐 클래스 소스 코드: Lib/queue.py The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queu

docs.python.org

https://codingpractices.tistory.com/entry/Python%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%99%9C-%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%8C%80%EC%8B%A0-%ED%81%90-%EB%8D%B0%ED%81%AC-deque-%EB%A5%BC-%EC%93%B8%EA%B9%8C

 

[Python]파이썬, 왜 리스트대신 큐/ 데크 deque 를 쓸까?

Python deque deque 라는 것은 쉽게 말하자면 파이썬의 list 와 같이 요소들을 한 곳에 담아두는 배열이다. 파이썬에서 큐 queue는 First In First Out (FIFO) 의 방식으로 작동된다. 덱(데큐)는 큐는 큐이지만

codingpractices.tistory.com

https://wikidocs.net/104977

 

008 앞뒤에서 자료를 넣고 빼려면? ― collections.deque

deque는 앞과 뒤에서 데이터를 처리할 수 있는 양방향 자료형으로, 스택(stack)처럼 써도 되고 큐(queue)처럼 써도 된다. collections.deque 모듈은 de…

wikidocs.net

 

728x90
반응형

댓글