113k views
5 votes
Suppose you are building a web application that allows users to create and manage to-do lists. You want to implement a stack data structure to keep track of the user's to-do items, giving the following list to-do:

["Buy groceries", "Do laundry", "Pay bills"]

Write a python program that do the following:

1. Creates an empty stack to store the to-do items. 2. Takes a to-do item and pushes it onto the top of the stack.

3. Print all items of stack.

4. Print only the top item from the stack without removing it. 5. Removes and returns the top item from the stack (pop item).

6. Check and print the number of items in the stack (size).

7. Check if stack empty or not and print "Stack is Empty" or "Stack is not Empty".

8. Removes and returns the top item from the stack (pop item).

9. Print all items of stack.

User TofuMaster
by
8.1k points

1 Answer

5 votes

Final answer:

A simple Python program to demonstrate a stack data structure for managing to-do list items, as well as essential stack operations such as push, pop, peek, and checking if the stack is empty.

Step-by-step explanation:

If you are building a web application that manages to-do lists using a stack data structure, here's a Python program to handle the operations as described:

  • Create an empty stack for to-do items.
  • Push a new item onto the stack.
  • Print all items in the stack.
  • Print the top item of the stack.
  • Pop an item from the stack.
  • Check and print the size of the stack.
  • Check if the stack is empty.
  • Pop another item from the stack.
  • Print the remaining items in the stack.

Here's how you would implement it:

stack = [] # Creates an empty stack
def push(item):
stack.append(item) # Adds an item
def print_stack():
print(stack) # Prints all items
def peek():
if stack:
print(stack[-1]) # Prints the top item
def pop_item():
if stack:
return stack.pop() # Removes the top item
else:
print("Stack is Empty")
def stack_size():
return len(stack) # Returns the size of the stack
def is_empty():
return len(stack) == 0 # Checks if stack is emptypush("Buy groceries")
push("Do laundry")
push("Pay bills")
print_stack()
peek()
print(f"Popped item: {pop_item()}")
print(f"Stack size: {stack_size()}")
print("Stack is Empty" if is_empty() else "Stack is not Empty")
print(f"Popped item: {pop_item()}")
print_stack()

This program demonstrates basic stack operations following a last in, first out (LIFO) principle.

User David Skelly
by
8.4k points

No related questions found