Computer scienceProgramming languagesPythonObject-oriented programmingMethods

Methods and attributes

Stack class

Report a typo

Whoa! This problem is much more complex than the usual one and requires knowledge of Stack (for example, the names of the methods are not random but related to Stack terminology). If you're feeling up to the challenge, brace yourself, and good luck! Otherwise, you can skip it for now and return any time later.

A stack is a data structure where elements are stored in the order in which they were added. A stack is like a stack of books or plates: you cannot remove any object, only the one that was added last.

Implement your Stack class in Python. It should wrap several built-in Python data structure and implement the following methods:

  • push(el): push a new element el to the stack;
  • pop(): remove and return the last element from the stack;
  • peek(): return the last element without removing it;
  • is_empty(): check if the stack is empty and return True or False.

The stack must be empty upon initialization. You don't need to create an instance of the class or print anything.

The tests implement the following sequence of operations on your class to test your code:

is_empty()
push(0)
push(1)
push(2)
push(3)
push(4)
pop()
pop()
peek()
pop()
is_empty()
Write a program in Python 3
class Stack:

def __init__(self):
pass

def push(self, el):
pass

def pop(self):
pass

def peek(self):
pass

def is_empty(self):
pass
___

Create a free account to access the full topic