Snippets

Camilo Rocha Stacks with shallow embedding

Created by Camilo Rocha
class stack(object):
  """stack implementation using a shallow embedding"""
  
  def __init__(self):
    """creates an empty stack in O(1)"""
    self.__stack = list()

  def __len__(self):
    """return the number of elements in the stack in O(1)"""
    return len(self.__stack)

  def __str__(self):
    """return the string representation of the stack in O(N)"""
    return str(self.__stack)

  def push(self,x):
    """adds x to the top of the stack in O(1)"""
    self.__stack.append(x)

  def top(self):
    """return the element last inserted in the stack in O(1)"""
    assert len(self)>0
    return self.__stack[-1]

  def pop(self):
    """remove the element last inserted in the stack in O(1)"""
    assert len(self)>0
    self.__stack.pop()

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.