+ 1
Python stack issue
In the stack operation code while inserting the element we are only giving it index 0 so how it's adding to the next indexes too. Problem is in push method : class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.insert(0, item) def pop(self): return self.items.pop(0) def print_stack(self): print(self.items) s = Stack() s.push('a') s.push('b') s.push('c') s.print_stack() s.pop() s.print_stack()
3 Respostas
+ 4
U r using insert (0,item)... It means that when ever u are pushing a item in stack it insert itself on index 0...
First you push 'a' in the stack it becomes
['a']
Now next you push 'b' , it will be insert in the 0 index that at position 1..
So now b is in 0 index and a goes on 1 index..
['b','a']
And so on
+ 2
Ok this means all the time every element will inserted at 0 and the element who were previously added will go one index ahead
Thanks Indira
+ 2
Anjali Singh yes....