Python Queue and Stack

Python Queue and Stack
Queque
  • FIFO: first-in first-out the oldest one is the first one to be taken out. two ends, put into one end, take out from another
  • enqueue: put one element into our queue
  • dequeue: take one element out from our queue
  • why we choose queue: real world services require fairness; essential perce in asynchronous computation to keep the same speed of the producer and consumer
Interface
class Queue(object):
  def __init__(self):
    self._items = [] #python we use _ to denominate private members, but it is not compulsory
  def __len__(self):
    return len(self._items)
  def enqueue(self, item):
    self._item.append(item)
  def dequeue(self):
    if self.empty():
      return None
    item = self._items[0]
    del self._items[0]
    return item
  def empty(self): #return True if our queue is empty. False otherwise
    return len(self._items) == 0
  def front(self): #returns the oldest element without removing it
    if self.empty():
      return None
    return self._items[0]
  • readability, maintainability
  • O(n) for dequeue; O(1) for all the rest
class ListNode(object):
  def __init__(self, value = None):
    self.next = None
    self.value = value

class Queue(object):
  def __init__(self):
    self._size = 0
    self._head, self_tail = None, None
  def _len_(self):
    return self._size
  def empty(self):
    return self._size == 0
  def enqueue(self, value):
    if not self.empty():
      self._tail.next = ListNode(value)
      self._tail = self._tail.next
    else:
      self._head = ListNode(value)
      self._tail = self._head
    self._size += 1
  def dequeue(self):
    if self.empty():
      return None
    value = self._head.value
    self._head = self._head.next
    if not self._head:
      self._tail = None
    self._size -= 1
    return value
  def front(self):
    if self.empty():
      return None
    return self._head.value
  • 也有用双下划线表示private self.__value 这样系统不能直接print
  • if O(1) to find the minimum number: effective query operation means that we need to do indexing and prepare all the answers in advance
  • Solution:
#deque means double-ended queue, it is an object
from collections import deque
class Queue(object):
  def __init__(self):
    self.__deque = deque()
    self.__mins = deque()
  def __len__(self):
    return len(self.__deque)
  def empty(self):
    return len(self.__deque) == 0
  def enqueue(self):
    self.__deque.append(value)
    while self.__mins and self.mins[-1] > value: #如果数组非空且最后一个元素大于当前value
      self.__mins.pop()
    self.__mins.append(value)
  def deque(self):
    value = self.__deque.popleft()
    #list del: O(n) 
    #deque,list pop: O(1)
    if value == self.__mins[0]:
      self.__mins.popleft()
    return value
  def front(self):
    return self.__deque[0]
  def min(self):
    return self.__mins[0]
#O(1) for enqueqe and dequeue
  • recommended: using deque to form queue, list to form stack
Stack
  • a pile of dishes: first-in-last-out
  • glossary:push and pop
class Stack(object):
  def __init__(self):
    self.__items = []
  def __len__(self):
    return len(self.__items)
  def empty(self):
    return len(self.__items) == 0
  def push(self, item):
    self.__items.append(item)
  def pop(self):
    if self.empty():
      return None
    return self.__items.pop()
  def top(self):
    if self.empty():
      return None
    return self.__items[-1] 
  • porblem 1: push 0-9 in order on to a stack, which ones are impossible:
    • 4,3,2,1,0,9,8,7,6,5 ok
    • 4,6,8,7,6,3,2,9,0,1 no 0,1
    • 2,5,6,7,4,8,9,3,1,0 ok
    • 4,3,1,0,5,6,7,8,9 ok
    • 0,4,6,5,3,8,1,7,2,9 no
  • problem 2: check brackets to find if they match, "{]" "[[})" are invalid
def is_valid(brackets):
  left_bracket = []
  matching_bracket = {'(' : ')', '{' : '}', '[' : ']'} #dictionary
  for b in brackets:
    if b in matching_bracket: #item in dictionary: look for the key
      left_bracket.append(b)
    elif not left_bracket or matching_bracket[left_bracket[-1]]:
#dictionary[key] = value
      return False
    else:
      left_bracket.pop()
  return not left_bracket #true only if empty
  • problem 3: Assuming we have the following definition for a concept called arithmetic expression:
    An arithmetic expression is either a number, or a left parentheis followed by an arithmetic expression followed by an operatot followed by another arithmetic expression followed by a right parentheis.
    The arithmetic expression itself will be represented as a list of strings that only contains the following terms: '(', ')', '+', '-', '', '/', non-negetive integers.
    input: ['(', '1', '+', '(', '5', '
    ', '4', ')', ')']
    output: 21
import operator
def arithmetic_expression_evaluation(terms):
  operands = [] #操作数
  operators = []
  ops = {'+' : operator.add, '-' : operator.sub, '*' : operator. mul, '/' : operator.truediv}
  for term in terms:
    if terms == '(':
      continue
    elif term == ')':
      right, left = operands.pop(), operands.pop()
      operands.append(ops[operators.pop()](left, right))
#operator.add(number1, number2)
    elif term in ops:
      operators.append(term)
    else:
      operands.append(int(term))
  return operands[0]
Homework

queue:leetcode 353 641 622
stack 150 155 224 225 232

Q: How to implement a queue using two stacks
image.png
class Queue:
  def __init__(self):
    self.s1 = []
    self.s2 = []
    self.head = None

def enqueue(self.x):
  if len(self.s1) == 0:
    self.head = x
  self.s1.append(x)

def deque(self):
   if len(self.s2) == 0:
    while self.s1:
      self.s2.append(self.s1.pop())
  return self.s2.pop()

def is_empty(self):
  return not self.s1 and not self.s2

def peek(self):
  if self.s2:
    return self.s2[len(s2) - 1]
  return self.head

def size(self):
  return len(self.s1) + len(self.s2)
  • enqueue time: O(1)
  • dequeue time: worst case: O(n) amortized: O(1) (same as using deque)
Q: implement a stack with MAX API

Soln1: brute-force: max() iterate each element in the stack to find the maximum
Soln2: trade space for time 把每一个stack成员变成tuple, (value, max)

class Stack:
  def __init__(self):
    self.stack = []

  def is_empty(self):
    return len(self.stack) == 0

  def max(self):
    if not self.is_empty():
      return self.stack[len(self.stack) - 1][1]
    raise Exception('max(): empty stack')

  def push(self, x)
    tmp = x
    if not self.is_empty():
      tmp = max(tmp, self.max())
    self.stack.append((x, tmp))

  def pop(self):
    if self.is_empty():
      raise Exception('pop(): empty stack')
    elem = self.stack.pop()
    return elem[0]
  • time: O(1) for each one
  • space: O(n) for each one
Q: non-recursion on tree tranversal: stack
def preorder_tranversal(root):
  output = []
  if not root:
    return output
  stack = [(root, 1)]
  while stack:
    node, count = stack.pop()
    if count == 1:
      output.append(node.val)
      stack.append((node, count + 1))
      if node.left:
        stack.append((node.left, 1))
    if count == 2:
      if node.right:
        stack.append((node.right, 1))
  return output
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,289评论 0 10
  • ️别人眼中的自己 是怎么样的呢? 为什么要在乎别人的眼光? 确实以前的自己有些方面还是很棒的 那么现在呢? 除了爱...
    好不好女孩阅读 921评论 0 0
  • 每一个真正的独立、自为思考的思想家就这一方面而言跟王侯相差无几:他的表达单刀直入,从来不会躲躲闪闪、畏首畏尾;他的...
    青竹子阅读 322评论 0 0
  • 狗是人们生活中的玩伴和伴侣,如何养好一只狗,让他健康快乐的成长,里面的学问可不小。 首先,我们要了解一些养狗的基本...
    极客游民阅读 288评论 0 2
  • 我是日记星球352号星宝宝,我正在参加日记星球星宝宝第十三期21天蜕变之旅,这是我的第7篇原创日记。如果你也想蜕变...
    彩虹老师阅读 9,898评论 1 2