-
85 - (파이썬) 스택과 큐study with Q - 파이썬 2024. 9. 9. 19:56
# 스택
:선입후출(First in Last out)(FILO) / 후입선출(Last in Fisst out)(LIFO) 구조를 갖는 자료 구조
박스에 책을 넣을때는 빨>파>초>노의 순으로 넣지만 다시 뺄 때는 노>초>파>빨의 순서로 빼게 된다.
푸시(push) : 스택에 자료를 넣는 행위
팝(pop) : 스택에서 자료를 꺼내는 행위
#스택 stack = Stack() stack.push("red") # ["red"] stack.push("blue") # ["red", "blue"] stack.push("green") # ["red", "blue", "green"] stack.push("yellow") # ["red", "blue", "green", "yellow"] stack.pop() # "yellow" ["red", "blue", "green"] stack.pop() # "green" ["red", "blue"] stack.pop() # "blue" ["red"] stack.pop() # "red"
# 스택 구현방법 예시
class Stack: def __init__(self): self.__list = [] def push(self, value): self.__list.append(value) def pop(self): output = self.__list[-1] del self.__list[-1] return output stack = Stack() stack.push("red") # ["red"] stack.push("blue") # ["red", "blue"] stack.push("green") # ["red", "blue", "green"] stack.push("yellow") # ["red", "blue", "green", "yellow"] print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) >>> yellow green blue red
# 큐
: 선입선출(First In First Out, FIFO)구조를 갖는 자료 구조
고속도로에 차가 들어갈 때 빨>파>초>노의 순으로 들어가면 나올 때도 빨>파>초>노의 순서로 나오게 된다.
인튜(enqueue) : 큐에 자료를 넣는 행위
디튜(dequeue) : 큐에서 자료를 꺼내는 행위
# 큐 구현방법 예시
class Queue: def __init__(self): self.__list = [] def enqueue(self, value): self.__list.append(value) def dequeue(self): output = self.__list[0] del self.__list[0] return output queque = Queue() queque.enqueue("R") queque.enqueue("B") queque.enqueue("G") queque.enqueue("Y") print(queque.dequeue()) print(queque.dequeue()) print(queque.dequeue()) print(queque.dequeue()) >>> R B G Y
'study with Q - 파이썬' 카테고리의 다른 글
88 - (파이썬) 기본 내장 모듈 (1) 2024.09.13 87 - (파이썬) 모듈을 읽는 방법 (0) 2024.09.13 83, 84 - (파이썬) 오버라이드와 super() 함수 / 상속과 컴포지션 (0) 2024.09.09 81 - 83 (파이썬) 강의 정리 포기, 코드 복붙 (1) 2024.09.01 80 - (파이썬) 클래스 문법 기본 (4) 2024.08.27