OkBublewrap

2024-12-05 TIL (큐) 본문

Today I Learning

2024-12-05 TIL (큐)

옥뽁뽁 2024. 12. 5. 09:19

Python - 큐

https://www.acmicpc.net/problem/18258

1. 배운 개념 / 주제

  • 스택이랑 비슷한 개념이다
  • 단, FIFO로 첫번째로 들어간게 첫번째로 나간다.
  • from collenctions import deque 패키지 활용

 

2. 배경 / 왜 배우게 되었는지

  • 파이썬 기초자료 공부

 

3. 핵심 내용.

  • 선입선출

 

4. 사용법 / 문제 풀이

# 개인 풀이
n = int(input())
que = []

for _ in range(n):
  s = input()

  if "push" in s:
    que.append(int(s[5:]))
  
  elif "pop" in s:
    if len(que) == 0:
      print(-1)
    else:
      print(que[0])
      que.remove(que[0])
      
  elif "size" in s:
    print(len(que))

  elif "empty" in s:
    if len(que) > 0:
      print(0)
    else:
      print(1)
  
  elif "front" in s:
    if len(que) == 0:
      print(-1)
    else:
      print(que[0])

  elif "back" in s:
    if len(que) == 0:
      print(-1)
    else:
      print(que[-1])
      
# 강의 풀이
from collections import deque

# 입력 데이터: 여러 줄의 입력을 한 번에 받음
input_data = """15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
"""

# 입력 데이터를 줄 단위로 나눔
input_lines = input_data.strip().split("\n")

# 첫 번째 줄은 명령어 개수 N
N = int(input_lines[0])

# 나머지 줄은 명령어들
commands = input_lines[1:] 

# 덱 초기화
d = deque()

# 명령어 처리
for command in commands:
    command = command.split()
    if command[0] == "push":
        d.append(command[1])
    elif command[0] == "pop":
        print("-1" if len(d) == 0 else d.popleft()) # que에 아무것도 없으면 -1 출력, 아니면 left에 넣은 데이터 삭제
    elif command[0] == "size": # 데이터 크기 출력
        print(len(d))
    elif command[0] == "empty": # 데이터 크기가 0이면 1, 아니면 0 출력
        print("1" if len(d) == 0 else "0")
    elif command[0] == "front": # 첫번째 데이터 출력
        print("-1" if len(d) == 0 else d[0])
    elif command[0] == "back":
        print("-1" if len(d) == 0 else d[-1]) # 마지막 데이터 출력

'Today I Learning' 카테고리의 다른 글

WIL - 2주차  (0) 2024.12.06
2024-12-06 TIL (화해 데이터 문해력 case study)  (0) 2024.12.06
2024-12-04 TIL (SQL - generate_series)  (0) 2024.12.04
2024-12-03 TIL (Python - Stack)  (0) 2024.12.03
2024-12-02 TIL (Funnel)  (0) 2024.12.02