john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

stack

# 2013-04-24 johnpfeiffer

class MyStack:

# TODO: CAPACITY
  EMPTY = -1

  def __init__( self ):
    self._stack = list()
    self._top = self.EMPTY

  def push( self, value ):
    self._top += 1
    self._stack.append( value )

  def pop( self ):
    if self._top > self.EMPTY:
      self._top -= 1
      return self._stack.pop()
    else:
      return None   # raise exception?



if __name__ == "__main__":
  print "BASIC TESTS of Stack operations"
  stack = MyStack()
  print "empty: ", stack._top, stack._stack
  assert None == stack.pop()   # empty stack pop should return None
  FIRST = 7
  SECOND = 6
  THIRD = 8
  stack.push( FIRST )
  assert stack._top == 0
  assert stack._stack[ 0 ] == FIRST
  print stack._top, stack._stack

  stack.push( SECOND )
  assert stack._top == 1
  assert stack._stack[ 1 ] == SECOND
  print stack._top, stack._stack

  assert SECOND == stack.pop()
  assert stack._top == 0
  assert stack._stack[ 0 ] == FIRST
  print stack._top, stack._stack

  stack.push( THIRD )
  assert stack._top == 1
  assert stack._stack[ 1 ] == THIRD
  print stack._top, stack._stack

  assert THIRD == stack.pop()
  assert FIRST == stack.pop()
  assert stack._top == -1
  print stack._top, stack._stack

  • « java programming intro main static systemProperties
  • palindromeTransformer test »

Published

Apr 24, 2013

Category

python

~130 words

Tags

  • python 180
  • stack 4