0

I have written the below code to implement the stack class instead of using the build in function, not sure if I have got it rigth. Can someone please check for me and advise if there is an error?

class DSAStack():

    maxCap = 100

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

        self.count = 0


    def isEmpty(self):
        if self.count == 0:
            return True
        else:
            return false


    def isFull(self):
        if self.count == maxCap:
            return True
        else:
            return false


    def push(self, item):
        if self.isFull:
            raise ('Stack is full...')
        else:
            self.stack[self.count] = item
            self.count += 1


    def pop(self):
        self.topVal = self.top
        self.stack[self.count - 1] = 0
        self.count = self.count - 1

        return self.topVal


    def top(self):
        if self.isEmpty:
            raise ('Stack is empty...')
        else:
            self.top = self.stack[self.count - 1]
14
  • 1
    you want to use "==" instead of "=" in comparison (look at your if statements)..... Commented Sep 4, 2020 at 3:17
  • Why does the __init__ method take parameters that it doesn't use? Commented Sep 4, 2020 at 3:21
  • self.count is always equal to len(self.stack), so isFull() will always return true. Commented Sep 4, 2020 at 3:22
  • What's the difference between self.topVal used in pop() and self.top used in top(). Also, you shouldn't assign an attribute with the same name as a method, it will replace the method. Commented Sep 4, 2020 at 3:24
  • you have an indentation error in pop(). Commented Sep 4, 2020 at 3:25

1 Answer 1

1

Firstly, you need not keep track of count. Accessing the length of the list will do that for you.

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

Now, your logic for isEmpty and isFull was alright, but since we are removing the self.count variable, here's how you'd go about it

def isEmpty(self):
    return len(self.stack) == 0 #Directly return true or false

def isFull(self):
    return len(self.stack) == maxCap #Directly return true or false

In your push function, there are a few things I'd like to point out. First, you need to call the isFull function. So we need to add parentheses to it.

Secondly, you cant just raise ('Stack is full...'), you will get a TypeError: Exceptions must derive from BaseException. This basically means what you raise must be some type of error.

Lastly, you can't add a new element by doing self.stack[self.count]=item since you will get an IndexError

Here are the changes:

def push(self,item):
    if self.isFull():    #Need to call the function, self.isFull is not a variable
        raise Exception('Stack is full...') #Or any other type of error
    else:
        self.stack.append(item)    #Adds new item to the end of self.stack

Now coming to the pop function, setting a value to zero in a list does not really get rid of it. And it can cause a lot of confusion, especially since we are using the len(self.stack) to implement this. Here's how you would pop:

def pop(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        return self.stack.pop() #List has a built-in pop method   

So now we don't really need the top function. And that concludes that. Btw, in your top function, you have defined self.top = self.stack[self.count-1] Giving the same name to a function and a variable is never really a good idea.

To implement the pop functionality yourself, you could do the following:

def pop(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        topVal = self.stack[-1] #-1 gives you the last element
        #if stack will contain objects instead of primitive data types, use self.stack[-1].copy()
        del self.stack[-1] #Deletes the element
        return topVal

Polishing your top function will be like this:

def top(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        return self.stack[-1]
def pop(self):
    topVal = self.top()
    del self.stack[-1]    
    return topVal    

Note how the top function is defined before the pop function. Also, try to test the code out and resolving any issues.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks heaps. Your answer is very helpful. The reason I do not use the pop inbulid function is this is part of my assignment requiement. The same for the top function. Can you please polish my top function if possible?
brilliant, that make sense. Why do I need to add .copy() if it is a stack of objects?
Nevermind, I was wrong seems like you don't need that 😅😅
i have modified my code a bit ,but when i run the test, the below error show up. #test 2 - push value 15 numtests += 1 ---> 16 s.push(100) 17 s.push(200) 18 if s.getcount() ==2: <ipython-input-10-e876b470f184> in push(self, value) 21 def push(self,value): 22 if self.isFull: ---> 23 raise Exception ('Stack is full...') 24 else: 25 temp = self.count Exception: Stack is full...
Umm okay... Can't really read this properly, do you have your code with the test cases on github??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.