def matching_brackets(string): bracket = Stack() bracket_dict = {"(": ")", "{": "}", "[": "]"} for char in string: if char in bracket_dict: bracket.push(char) elif char in [")", "}", "]"]: if bracket.isEmpty(): return False if bracket_dict[bracket.peek()] == char: bracket.pop() else: return False if not bracket.isEmpty(): return False return True
def graph_depth_first(self, vertex): if vertex not in self.get_vertices(): return f"{vertex} is not in graph" vertex_stack = Stack() visited_list = [vertex] vertex_stack.push(vertex) while not vertex_stack.isEmpty(): new_vertex = vertex_stack.peek() new_vertex_neighbors = self.get_neighbors(new_vertex) counter = 0 for edge in new_vertex_neighbors: vert, wt = edge.split(" ") if vert not in visited_list: vertex_stack.push(vert) visited_list.append(vert) counter += 1 if counter == 0: vertex_stack.pop() return visited_list
def multi_bracket_validation(input_string): br_dict = {'}': '{', ')': "(", ']': "["} if input_string == "": return False _stack = Stack() _stack_length = 0 for chr in input_string: if chr in br_dict: if br_dict[chr] == _stack.peek(): _stack.pop() else: return False elif chr in br_dict.values(): _stack.push(chr) _stack_length += 1 if _stack_length == 0: return "no brackets in string" elif _stack.isEmpty(): return True return False
def is_palindrome(ll): mid = ll.head scout = ll.head pal = Stack() # get the stack set up while scout.next: pal.push(mid.value) if scout.next.next: scout = scout.next.next mid = mid.next else: break mid = mid.next while mid: if mid.value == pal.peek(): pal.pop() mid = mid.next else: return False return True
def test_Stack_push_newValue(): fruit = Stack() fruit.push("apples") actual = str(fruit) expected = "{apples} -> NULL" assert actual == expected
def test_Stack_instantiate_empty_stack(): fruits = Stack() actual = str(fruits) expected = "NULL" assert actual == expected
def fruit_stack(): fruit_stack = Stack() fruit_stack.push("apples") fruit_stack.push("bananas") return fruit_stack
def empty_stack(): empty_stack = Stack() return empty_stack
def __init__(self): self.stack_to_enqueue = Stack() self.stack_to_dequeue = Stack()
class PseudoQueue: def __init__(self): self.stack_to_enqueue = Stack() self.stack_to_dequeue = Stack() def enqueue(self, new_val, *args): while not self.stack_to_dequeue.isEmpty(): self.stack_to_enqueue.push(self.stack_to_dequeue.pop()) self.stack_to_enqueue.push(new_val, *args) return def dequeue(self): while not self.stack_to_enqueue.isEmpty(): self.stack_to_dequeue.push(self.stack_to_enqueue.pop()) if self.stack_to_dequeue.isEmpty(): raise RuntimeError("cannot dequeue from empty queue") return self.stack_to_dequeue.pop() def __str__(self): """ { a } -> { b } -> { c } -> NULL """ final_string = "" while not self.stack_to_dequeue.isEmpty(): self.stack_to_enqueue.push(self.stack_to_dequeue.pop()) current = self.stack_to_enqueue.top while current: final_string += f" <-- {{{current.value}}} " current = current.next return f"NULL{final_string}"