0

I was trying to implement Stack via array using Python. Here is my code.

class Stack:

    def init(self,top,size):
        self.size =  4
        self.top = []

    def isEmpty(self):
        if len(self.top) == 0:
            return True
        else:
            return False 
    def length(self):
        return len(self.top)
    def peek(self):
        if self.Empty() == True :
            print("Cannot peek at an empty Stack")
        else:
            return self.size[len(self.top)]    
    def pop(self):
        if self.isEmpty():
            print("Cannot peek at an empty Stack")
        else:
            value = self.size[len(self.top)-1]
            del self.top[len(self.data) - 1]
            return value
    def push(self, item):
        if len(self.top) >= self.size:
            print("Cannot push. Stack is full")
        else:
            self.top.append(item)

s = Stack()

Whenever I try to use operations such as push, pop etc.. I get an error saying 'Stack object has no attribute top.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • It's not the immediate cause of your current exception, but `self.size[len(self.top)-1]` and similar is complete nonsense. `self.size` is an integer, you can't index it. I'm pretty sure you always want to be indexing with `self.top[-1]`. – Blckknght Jul 24 '16 at 01:25

1 Answers1

0

You need to call your init() method __init__().

Also you should inherit from object as per: Should all Python classes extend object? e.g.:

class Stack(object):
    def __init__(self,top,size):
        # ...

Furthermore I do not understand why you have arguments for top and size and yet you populate them with [] and 4. You could instead pass in size on instantiation, and by default have top be a list e.g.:

class Stack(object):
    def __init__(self,size):
        self.size = size
        self.top = []
Community
  • 1
  • 1
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223