Example #1
0
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}"
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
Example #3
0
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