Stacks and Queues in Python
程序员文章站
2024-03-01 13:34:10
...
1. 在python中,stack和queque都可以通过list来实现
- push()都可以通过 list.append() 来实现
- 对于stack,pop直接通过 list.pop() 实现,而对于queque,则使用 list.pop(0)
2. 还可以用deque来实现stack和queque
- pop like a stack: .pop()
- pop like a queque: .popleft()
from collections import deque
# initialize a deque
numbers = deque()
# Use append like before to add elements
numbers.append(99)
numbers.append(15)
numbers.append(82)
numbers.append(50)
numbers.append(47)
# You can pop like a stack
last_item = numbers.pop()
print(last_item) # 47
print(numbers) # deque([99, 15, 82, 50])
# You can dequeue like a queue
first_item = numbers.popleft()
print(first_item) # 99
print(numbers) # deque([15, 82, 50])
3. 定义class来严格地定义stack和queque
class Stack:
def __init__(self):
self.stack=[]
def pop(self):
if len(self.stack)<1:
return None
return self.stack.pop()
def push(self,item):
self.stack.append(item)
document_actions = Stack()
# The first enters the title of the document
document_actions.push('action: enter; text_id: 1; text: This is my favourite document')
# Next they center the text
document_actions.push('action: format; text_id: 1; alignment: center')
# As with most writers, the user is unhappy with the first draft and undoes the center alignment
document_actions.pop()
print(document_actions.stack)
# The title is better on the left with bold font
document_actions.push('action: format; text_id: 1; style: bold')
print(document_actions.stack)
class Queue:
def __init__(self):
self.queue=[]
def enqueue(self,item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
input_queue = Queue()
# The player wants to get the upper hand so pressing the right combination of buttons quickly
input_queue.enqueue('DOWN')
input_queue.enqueue('RIGHT')
input_queue.enqueue('B')
# Now we can process each item in the queue by dequeueing them
key_pressed = input_queue.dequeue() # 'DOWN'
# We'll probably change our player position
key_pressed = input_queue.dequeue() # 'RIGHT'
print(key_pressed)
# We'll change the player's position again and keep track of a potential special move to perform
key_pressed = input_queue.dequeue() # 'B'
print(key_pressed)
# This can do the act, but the game's logic will know to do the special move
上一篇: Golang Slice
下一篇: 不借用第三个变量,如何交换两个变量的值