Python Class for a Stack Data Structure

This technical problem deals with implementing a stack data structure in Python using a class. The class should have two methods: push, which adds an item to the top of the stack, and pop , which removes and returns the top item from the stack. If the stack is empty, pop should raise an IndexError.

Problem

Given a list of integers, write a Python class to represent a stack (a last-in, first-out data structure). Your class should have two methods:
- push(self, item), which adds the given item to the top of the stack
- pop(self), which removes and returns the top item from the stack. If the stack is empty, this method should raise an IndexError.
Example input:
[1, 2, 3]
Example output:
3
2
1

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
class Stack:
    def __init__(self, items):
        self.items = items

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if len(self.items) == 0:
            raise IndexError
        return self.items.pop()

stack = Stack([1, 2, 3])
print(stack.pop())
print(stack.pop())
print(stack.pop())

# The solution is optimal because it uses the built-in list data structure to store the items in the stack.
# The list is a dynamic array, which means that it can grow and shrink in size as needed.
# The push method is O(1) because it simply appends the item to the end of the list.
# The pop method is O(1) because it simply removes the last item from the list.

A.I. Evaluation of the Solution

The candidate's solution is optimal because it uses the built-in list data structure to store the items in the stack. The list is a dynamic array, which means that it can grow and shrink in size as needed. The push method is O(1) because it simply appends the item to the end of the list. The pop method is O(1) because it simply removes the last item from the list.

Evaluated at: 2022-11-13 02:16:05