Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Stack python

"""Stack
Stack is a Last In - First Out (LIFO) data structure, much like stacking.
  - The below is a simple class implementation of it

Check out the source for more info!
"""

class Stk:
    def __init__(self):
        self.s = [] # empty lst

    def push(self, data): # Insert new data
        self.s.append(data)
    
    def pop(self): # Remove latest data
        if self.s:
            return self.s.pop()
        return "Empty!"
    
    def peek(self): # See latest data
        if self.s:
            return self.s[-1]
        return "Empty!"
    
    def size(self): # find size
        return len(self.s)
    
    def display(self):
        return self.s

# Test
from random import randrange
def Stk_Test(stk):
    # Create random list
    lst = [randrange(10, 100) for _ in range(10)]
    print(f"List: {lst}")
    
    # Create Empty Stack
    S = stk()
    print(f"Stk: {S.display()}", 
          f"Size: {S.size()}", 
          f"Top: {S.peek()}",
          sep = " | ", end = "

")
    
    # Put items into stack
    for item in lst: 
        S.push(item)
    print(f"Top: {S.peek()}", 
          f"Stk: {S.display()}",
          sep = " | ", end = "

")
    
    # Remove items from stack
    for _ in range(len(lst)): 
        print(f"Popped: {S.pop()}", 
              f"Top: {S.peek()}", 
              f"Size: {S.size()}", 
              f"Stk: {S.display()}",
              sep = " | ")
    
Stk_Test(Stk)
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #Stack #python
ADD COMMENT
Topic
Name
3+5 =