Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack data structure in python

Tags:

python

I have 2 issues with the code below:

  1. push(o) throws an exception TypeError: can only assign an iterable.
  2. Should I throw an exception if pop() is invoked on an empty stack ?

    class Stack(object):      def __init__(self):         self.storage = []      def isEmpty(self):         return len(self.storage) == 0      def push(self,p):         self.storage[:0] = p      def pop(self):         """issue: throw exception?"""         return None 
like image 435
Frankie Ribery Avatar asked Jan 14 '11 07:01

Frankie Ribery


People also ask

What is stack data structure in Python?

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.

What are the 4 data structures in Python?

The basic Python data structures in Python include list, set, tuples, and dictionary. Each of the data structures is unique in its own way. Data structures are “containers” that organize and group data according to type.

What is the structure of a stack?

The stack data structure is a linear data structure that accompanies a principle known as LIFO (Last In First Out) or FILO (First In Last Out). Real-life examples of a stack are a deck of cards, piles of books, piles of money, and many more.

Is there a stack module in Python?

deque to Create a Python Stack. The collections module contains deque , which is useful for creating Python stacks. deque is pronounced “deck” and stands for “double-ended queue.”


2 Answers

No need to jump through these loops, See 5.1.1 Using Lists as Stacks

If you insist on having methods isEmpty() and push() you can do:

class stack(list):     def push(self, item):         self.append(item)     def isEmpty(self):         return not self 
like image 138
Kimvais Avatar answered Sep 28 '22 05:09

Kimvais


You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.

class Stack:   def __init__(self):     self.__storage = []    def isEmpty(self):     return len(self.__storage) == 0    def push(self,p):     self.__storage.append(p)    def pop(self):     return self.__storage.pop() 

This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.

like image 23
Matthieu M. Avatar answered Sep 28 '22 06:09

Matthieu M.