Answers for "python stack implementation"

1

best python stack implementation

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

     def isEmpty(self):
         return self.items == []

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

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)
Posted by: Guest on February-04-2021
7

stack data structure python

#using doubly linked list
from collections import deque
myStack = deque()

myStack.append('a')
myStack.append('b')
myStack.append('c')

myStack
deque(['a', 'b', 'c'])

myStack.pop()
'c'
myStack.pop()
'b'
myStack.pop()
'a'

myStack.pop()

#Traceback (most recent call last):
 #File "<console>", line 1, in <module>
##IndexError: pop from an empty deque
Posted by: Guest on January-05-2020
1

def dft(self, array): stack = Stack() visited = set() stack.append(self) while len(stack) > 0 and while len(visited) >= 0: current = stack.pop() array.append(current) visited.add(current) return array

def dft(self, array):
    stack = Stack()
    visited = set()
    stack.append(self)
    while len(stack) > 0 and while len(visited) >= 0:
        current = stack.pop()
        array.append(current)
        visited.add(current)
    return array
Posted by: Guest on March-03-2020
1

stack in python

stack = []
# add element in the stack.
stack.append('a')
# delete in LIFO order.
stack.pop()
Posted by: Guest on August-07-2021
0

python dijkstra implementation stack

nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
distances = {
    'B': {'A': 5, 'D': 1, 'G': 2},
    'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5},
    'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3},
    'G': {'B': 2, 'D': 1, 'C': 2},
    'C': {'G': 2, 'E': 1, 'F': 16},
    'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2},
    'F': {'A': 5, 'E': 2, 'C': 16}}

unvisited = {node: None for node in nodes} #using None as +inf
visited = {}
current = 'B'
currentDistance = 0
unvisited[current] = currentDistance

while True:
    for neighbour, distance in distances[current].items():
        if neighbour not in unvisited: continue
        newDistance = currentDistance + distance
        if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
            unvisited[neighbour] = newDistance
    visited[current] = currentDistance
    del unvisited[current]
    if not unvisited: break
    candidates = [node for node in unvisited.items() if node[1]]
    current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]

print(visited)
Posted by: Guest on August-03-2020

Code answers related to "python stack implementation"

Python Answers by Framework

Browse Popular Code Answers by Language