Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python stack class

class Stack():
    def __init__(self, list = []):
        self._stack = list
        
    def push(self, item):
        if(hasattr(item, "__getitem__")):
            self._stack.extend(item)        
        else:
            self._stack.append(item)
        
    def isEmpty(self):
        return not self._stack
    
    def pop(self):
        if(self.isEmpty()):
            return None
        return self._stack.pop()
    
    def peek(self):
        if(self.isEmpty()):
            return None
        return self._stack[-1]
    
    def size(self):
        return len(self._stack)
Comment

python stack

from collections import deque

the_stack = deque()

# this function can serve as push
the_stack.append("data")
print(the_stack.pop()) # -> data

# Check out the documents for more features coming when using that dedicated
# builtin.

# About deque: Deques are a generalization of stacks and queues
# (the name is pronounced “deck” and is short for “double-ended queue”).
# Deques support thread-safe, memory efficient appends and pops from either
# side of the deque with approximately the same O(1) performance in either
# direction.
Comment

stack in python

# Special note: I've coded different types of code to explain the stack.
# So, you can use the code that will help you understand. Thank you. Happy coding.

# Stack:
# Stack main structure = Last in First Out..
# 1st system easy code and Main Code:

class Stack:
    def __init__(self):
        self.items = []

    # items check the None:
    def is_empty(self):
        if self.items == []:
            return True
        else:
            return False

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

    # item delete or pop:
    def delete(self):
        return self.items.pop()
if __name__ == "__main__":
    s = Stack()
    s.push(2)
    s.push(3)
    s.push(4)
    while not s.is_empty():
        item = s.delete()
        print(item)
#Programe Finished.


# Stack details system code...
'''
 stack = []
 
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
 
print('Initial stack')
print(stack)
 
# pop() function to pop
# element from stack in 
# LIFO order
print('
Elements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
 
print('
Stack after elements are popped:')
print(stack)
 
# uncommenting print(stack.pop())  
# will cause an IndexError 
# as the stack is now empty

'''


# Stack details system: But, used not definition and class:
# just for understand.


'''
li = []
for _ in range(int(input())):
    print("Last in append:")
    li.append(int(input()))
while len(li)>1:
    print(li)
    li.pop()
    print("First out = ",li)
print("First out = ",li)
'''
# Stack Example and 2nd system:
'''
class My_stack():
    def __init__(self):
        self.data = []
    def my_push(self, x):
        return (self.data.append(x))
    def my_pop(self):
        return (self.data.pop())
    def my_peak(self):
        return (self.data[-1])
    def my_contains(self, x):
        return (self.data.count(x))
    def my_show_all(self):
        return (self.data)

arrStack = My_stack()     
arrStack.my_push(1)
arrStack.my_push(2)
arrStack.my_push(1)
arrStack.my_push(3)
print(arrStack.my_show_all())
arrStack.my_pop()
print(arrStack.my_show_all())
print(arrStack.my_contains(1))
'''


# Stack 3rd system:
# Stack main structure = Last in First Out..


'''
class Stack:

    def __init__(self):
        self.Stack = []
        self.size = 0

    def DataAdd(self, new_data):
        self.Stack.append(new_data)
        self.size += 1

    def outElement(self):
        self.size -= 1
        return self.Stack.pop()

    def isEmptySTack(self):
        if self.size == 0:
            return "Stack is Empty!"
        else:
            return "Stack is Full"

    def print_Stack(self):
        return self.Stack


    def firstData(self):
        return self.Stack[0]


    def LastData(self):
        return self.Stack[-1]
     
     # Reversing korar jonno
    def ReversedStack(self):
        return self.Stack[::-1]

if __name__ == "__main__":
    op = Stack()

    # add data
    op.DataAdd('0. English')
    op.DataAdd("1. Bangla")
    op.DataAdd("2. Math")
    op.DataAdd("3. Islam")
    op.DataAdd("4. Hindi")


    print("Before Stack:", op.print_Stack())
    print("Before Stack Size", op.size)
    print()

    # remove Data
    op.outElement()
    op.outElement() # 2 element remove
    print("After Stack", op.print_Stack())
    print("After Stack Size", op.size)

    # Stack Size
    print(op.size)
    # Reversed Stack
    print("Reversed Stack", op.ReversedStack())

    # Stack First Data
    print("This is Stack First Element", op.firstData())
    print("This is Stack Last Element", op.LastData())

'''

# Stuck Example to 4th system...

'''
class BBPI:

    def __init__(self, name, roll, id):
        self.Name = name
        self.Roll = roll
        self.Id = id

    def CMT(self):
        return self.Name, self.Roll, self.Id


    def EMT(self):
        return self.Name, self.Roll, self.Id


    def RAT(self):
        pass


class CPI(BBPI):

    def emt(self):
        return self.Name, self.Roll, self.Id

# Driver Code
if _name_ == '_main_':

    op = BBPI("Murad", 165090, 677312838)
    op1 = BBPI("kamal", 214231, 124535221)

    print(op.CMT())
    print(op1.EMT())


    print("CPI")
    o = CPI("a", 121, 11)
    print(o.emt())
'''

# Stack 5th system example and easy system to code:


'''
class Stack:
    def __init__(self):
        self.list = []
    
    def emty_list(self):
        if self.list == []:
            return True
        else:
            return False
    def data_append(self,data):
        self.list.append(data)

    def data_delete(self):
        return self.list.pop()

s = Stack()
s.data_append(3)
s.data_append(4)
s.data_append(5)
while not s.emty_list():
    print(s.data_delete())
'''
Comment

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)
Comment

PREVIOUS NEXT
Code Example
Python :: pandas df num rows 
Python :: dictionary indexing python 
Python :: pandas date range 
Python :: write binary file in python 
Python :: iterate over dictionary django 
Python :: def function in python 
Python :: make zipfile from directory py 
Python :: cross join pandas 
Python :: openai python 
Python :: object value python 
Python :: fcm_django 
Python :: python replace nth occurrence in string 
Python :: Display if the column(s) contain duplicates in the DataFrame 
Python :: catch error data with except python 
Python :: pygame.draw.rect() 
Python :: how to use cos in python 
Python :: how to install python dill 
Python :: what is self in python 
Python :: run python.py file 
Python :: suppress python vs try/except pass 
Python :: catalan number 
Python :: Auto-removal of grids by pcolor() and pcolormesh() is deprecated since 3.5 and will be removed two minor releases later; please call grid(False) first. 
Python :: replace outliers with nan python 
Python :: pandas remove leading trailing spaces in dataframe 
Python :: how to run python program in sublime text 3 windows 
Python :: python random randint string 
Python :: python file hashlib 
Python :: random int python 
Python :: sqlalchemy filter between dates 
Python :: if statement in one-line for loop python 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =