2
\$\begingroup\$

Problem : Implement a stack class in Python. It should support 3 APIs:

stack.top(): prints element at top of stack

stack.pop(): takes out an element from top of stack,

stack.push(): adds a new element at top of stack

Does this code covers all the edge cases of implementing a stack?

class Stack():

    def __init__(self):
        self.item = []

    def size(self):
        return len(self.item)

    def top(self):
        if len(self.item) >= 1:
            print self.item[len(self.item) -1]
        else :
            print "Empty list"

    def pop(self):
        if len(self.item) >= 1:
            self.item.pop()
        else:
            raise IndexError 

    def push(self,item):
        self.item.append(item)
        print self.item


new_stack = Stack()
new_stack.push(19)
new_stack.push(20)
new_stack.push(119)
new_stack.push(202)
new_stack.push(195)
new_stack.push(205)
new_stack.push(149)
new_stack.push(230)

print new_stack.size()
new_stack.top()
new_stack.pop()
new_stack.top()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.top()
\$\endgroup\$
  • 6
    \$\begingroup\$ You've not really implemented a stack. You've just made an interface to a list... \$\endgroup\$ – Peilonrayz Jan 23 '18 at 17:17
2
\$\begingroup\$

Thanks for sharing your code,

instead of using size, you should implement __len__, this way you can use len(my_stack).

def __len__(self):
    return len(self.item)

I think a method that prints an element from a collection is a bit unusual. What I would expect is a method called peek that returns the top element but doesn't remove it. By just printing it you're limiting its use to console only applications, and the only way to retrieve the element is to remove it!

You should consider adding an error message to go with your IndexError, and maybe reconsider the exception type, an IndexError sounds like you're accessing an index, but you're not maybe a custom StackEmpty exception would be more suitable.

I think self.item should be self.items (plural) as it will be representing zero or more items.

Bonus Stuff

you could implement the __iter__ method. This would allow the caller to do something like

for element in my_stack:
    do_stuff()

You code is also missing docstrings, you could optionally add those to document your code.

You could implement the __str__ method to provide a nice string representation so you can simply say

print my_stack

Hopefully you found this helpful, keep it up!

\$\endgroup\$
0
\$\begingroup\$

You can simplify your top function like the code below.

def top(self):
    if self.item:              # if len > 0 it will evaluate to True
        print self.item[-1]    # -1 refer to the last item
    else :
        print "Empty list"
\$\endgroup\$
0
\$\begingroup\$

I do not like the code and question itself. If we are to implement a stack, then it needs to be implemented through and through. Using all of the already defined names and methods from list means that nothing is actually being implemented. All that is being done is we have changed the name list to Stack.

To properly implement a stack, you will want to make a Circular Linked List, with nodes (where nodes are defined in a class Nodes). To make a Circular Linked List, just make a class LinkedList such that self.head and self.tail are defined, and when self.stacksize is full, have:

self.tail.next = self.head
self.head = Node(value, prevNode, nextNode)

To begin the LinkedList class:

class LinkedList:
  def __init__(self, value=None, stacksize=10):
    self.stacksize = stacksize
    self.tail      = None
    self.head      = None
    self.curIndex  = -1 #Dropping support for negative indexing
    if value is not None:
      self.append(value)
  '''
  TODO METHODS:
  def __eq__(self, other):
  def __str__(self):
  def __iter__(self):
  def isfull(self):
  '''
  def append(self, value):
    ''' append to last inserted node '''
    self.curIndex += 1
    if self.head is None:
      self.head = self.tail = Node(value, None, None)
    elif self.isFull():
      ''' write a method returning self.tail.index == self.stacksize'''
      if self.curIndex == self.stacksize:
         self.curIndex -= self.stacksize
      self.tail.next = Node(value, self.tail, self.head.next)
      self.head = self.tail.next
    else:
      self.tail.next = Node(value, self.tail, None)
    return self.tail

And then class Node...

class Node:
  def __init__(self, value=None, prev=None, next=None, index=0):
    self.value = value
    self.prev = prev
    self.next = next
    if prev:
      index = prev.index+1
    self.index = index
  '''
  TODO METHODS:
  def __eq__(self, other):
  def __str__(self):
  def __iter__(self):
  '''
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.