Why the little change of top will lead a error "Index out of range"?(python)


  • 0
    Q

    If I write my code like this, it will be accepted:

    @return nothing

    def pop(self):
    	top = self.top()
    	self.stack.pop()
    	if top == self.minstack[-1]:
    		self.minstack.pop()
    

    If I change like this, there is an error throw:

    @return nothing

    def pop(self):
    	self.stack.pop()
    	if self.top() == self.minstack[-1]:
    		self.minstack.pop()
    

    Is anybody know why such error generate? I just have no idea and think it is almost the same. Thanks~


  • 0
    B

    your first code is different with the second one.
    for example,the current stack is [1,2,3,4,5]:
    execute 'top=self.top()',top is 5 ,then compare with self.minstack[-1] is right
    but,in your second code,after execute self.stack.pop(), self.top() equals 4,it's different with your first code 's top which is equals 5


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.