you will write a class (Stack) that implements all of the stack operations descr
ID: 3938524 • Letter: Y
Question
you will write a class (Stack) that implements all of the stack operations described in the lectures. Those operations are provided, below: top (): Returns the top of the stack pop (): Removes and returns the top of the stack push(): Places a new element on top of the stack isEmpty(): Returns True if the stack is empty Use the following code to test your stack: stack = Stack() print('isEmpty():', stack.isEmpty()) print('empty:', stack) stack.push(1) print('after push(l):', stack) print('isEmpty():', stack.isEmpty()) stack.push(10) print('after push(10):', stack) print('pop():', stack.pop()) print('after pop():', stack) stack.push(2) print('after push(2):', stack) stack.push(3) print('after push(3):', stack) stack.push(4) print('after push(4):', stack) print('pop():', stack.pop()) print('after pop():', stack) print('pop():', stack.pop()) print('after pop():', stack) print('pop():', stack.pop()) print('after pop():', stack) print('pop():', stack.pop()) print('after pop():', stack) print('isEmpty():', stack.isEmpty())Explanation / Answer
Code:
class myStack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.container.append(item)
def pop(self):
return self.container.pop()
def top(self):
return self.container[len(self.container)-1]
s= myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.top())
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.