Skip to content
The Chat Archive
qwen3-235b-a22b-no-thinking· Alibaba (Qwen) LMArena Human Preference 140K

a. Implement a stack data structure in Python using lists and provide functions for…

  1. User

    a. Implement a stack data structure in Python using lists and provide functions for push, pop, and peek operations. b. Write a Python function to reverse a string using a stack

  2. Assistant

    Sure! Let's go step-by-step.


    a. Implement a Stack Data Structure in Python Using Lists

    In Python, a stack can be easily implemented using a list. Here's how you can define a stack class with push, pop, and peek operations:

    class Stack:
        def __init__(self):
            self.items = []
    
        def is_empty(self):
            return len(self.items) == 0
    
        def push(self, item):
            self.items.append(item)
    
        def pop(self):
            if not self.is_empty():
                return self.items.pop()
            else:
                raise IndexError("Pop from an empty stack")
    
        def peek(self):
            if not self.is_empty():
                return self.items[-1]
            else:
                raise IndexError("Peek from an empty stack")
    
        def size(self):
            return len(self.items)
    
        def __str__(self):
            return str(self.items)
    

    Example Usage:

    stack = Stack()
    stack.push(10)
    stack.push(20)
    stack.push(30)
    
    print("Top element:", stack.peek())  # Output: 30
    print("Popped:", stack.pop())       # Output: 30
    print("Stack after pop:", stack)    # Output: [10, 20]
    

    b. Function to Reverse a String Using a Stack

    Now let's write a function that uses the stack to reverse a string:

    def reverse_string(s):
        stack = Stack()
    
        # Push all characters of the string onto the stack
        for char in s:
            stack.push(char)
    
        # Pop characters from the stack and build reversed string
        reversed_str = ''
        while not stack.is_empty():
            reversed_str += stack.pop()
    
        return reversed_str
    

    Example Usage:

    original = "hello"
    reversed_str = reverse_string(original)
    print("Original:", original)      # Output: hello
    print("Reversed:", reversed_str) # Output: olleh
    

    ✅ Summary

    • You now have a working Stack class with essential operations.
    • You also have a function reverse_string that uses this stack to reverse any given string.

    Let me know if you'd like to add more features (e.g., stack limit, error handling, etc.)!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.