Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

64 lines (46 sloc) 2.075 kb

stack.py

A real stack collection for Python. Sometimes you don't want something that walks like a duck, that swims like a duck and that quacks like a duck. Sometimes you just want a duck!

There are unit tests available in stacktests.py. There is one example of using the stack to implement a basic reverse polish notation calculator in the examples folder.

Justification

Some algorithms are best implemented using a stack and while it is possible to use a built-in list() like a stack, I find the semantics of peek, my_list[-1], to be detracting from an algorithm's implementation. This Stack implementation provides the basic stack operations you learned in CS101:

  • .push()
  • .peek()
  • .pop()
  • .is_empty()

It also provides some conveniences:

  • .push(*objs) <-- push splat, multiple objects in one push
  • .reverse() <-- reverse the order of the stack. It is surprising how often you need to do this
  • .iter_pop() <-- returns a generator that pops the whole stack one item at a time

I don't recommend using this Stack implementation when your stack usage only loosely resembles a traditional stack though. For instance, when you are inserting into the middle of the list, popping the end of it and then slicing it out to chunks, etc... in those cases just tough it out with a regular list object as I think it will be faster for other Pythonistas to read your code.

Usage

from stack import Stack, EmptyStackException

stack = Stack()

# push one item
stack.push("a")

# push many items
stack.push("b", "c")
stack.push(*range(3))

# peek the top item
print(stack.peek())

# check the length
print(len(stack.peek()))

# reverse the stack in place
stack.reverse()

# pop an item
print(stack.pop())

# pop all of the items
items = [i for i in stack.iter_pop()]

# catch those exceptions, your algorithm should not try to do this!
empty_stack = Stack()
try:
  empty_stack.peek()
  empty_stack.pop()
  empty_stack.iter_pop()
  empty_stack.reverse()
except EmptyStackException as ese:
  print("Why'd ya do it man?")
Jump to Line
Something went wrong with that request. Please try again.