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

implement stack using list 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

implement stack using list in python

# Stack is Last In First Out data structure
stack = []

stack.append(1)
stack.append(2)
stack.append(3)  # 3 is top element of stack at this point

print(stack)  # [1, 2, 3]

top_element = stack.pop()
print(top_element)  # 3
print(stack.pop())  # 2
print(stack.pop())  # 1

print("Stack after being emptied: ")
print(stack)  # []
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 :: ngnix config 
Python :: Is python statically typed language? 
Python :: yaml validator python 
Python :: string.format() with {} inside string as string 
Python :: prevent selenium from closing 
Python :: python length 
Python :: bot delete embed py 
Python :: 2d list in python 
Python :: for char in string python 
Python :: how to get data after last slash in python 
Python :: python type checking 
Python :: get length of string python 
Python :: excel with python 
Python :: python print empty line 
Python :: python linux script 
Python :: pandas grid subplots 
Python :: tkinter hide widget 
Python :: python gui kivvy 
Python :: validationerror django params 
Python :: linear regression python code 
Python :: Install Pip 2 on ubuntu linux 
Python :: python replace string with int in list 
Python :: list comprehensions 
Python :: multiple assessment in python 
Python :: change gles3 to gles2 
Python :: pandas join two dataframes 
Python :: how to use python to download files from the interent 
Python :: cv2 and PIL BRG to RGB 
Python :: how to make a python file run in the background 
Python :: pandas options 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =