Exemplo n.º 1
0
def is_balanced(parens: str):
    """Checks to see if a string of parens are balanced"""
    stack = Stack()

    try:
        for paren in parens:
            if stack.is_empty() or (not stack.is_empty() and paren == stack.peek()):
                stack.push(paren)
            else:
                stack.pop()
        return stack.is_empty()
    except IndexError:
        return False
def interleave_queue(queue):
    half_size = queue.size // 2
    stk = Stack.Stack()
    for i in range(0, half_size):
        stk.push(queue.dequeue().get_data())
    stk.print_stack()
    queue.print_queue()
    print "----------------------"
    while stk.size > 0:
        queue.enqueue(stk.pop().get_data())
    stk.print_stack()
    queue.print_queue()
    print "----------------------"

    for i in range(0, queue.size -
                   half_size):  ### note this point.... queue.size - half_size
        queue.enqueue(queue.dequeue().get_data())

    for i in range(0, half_size):
        stk.push(queue.dequeue().get_data())

    stk.print_stack()
    queue.print_queue()
    result = []
    while stk.size > 0:
        result.append(stk.pop().get_data())
        result.append(queue.dequeue().get_data())

    if queue.size > 0:
        result.append(queue.dequeue().get_data())
    print result
Exemplo n.º 3
0
 def reverse_level_order(self):
     to_traverse = [self.root]
     stack = Stack(100)
     while len(to_traverse) > 0:
         node = to_traverse[0]
         data = node.value
         stack.push(Node(data))
         if node.right:
             to_traverse.append(node.right)
         if node.left:
             to_traverse.append(node.left)
         to_traverse.pop(0)
     traversal = []
     for x in range(stack.size):
         traversal.append(stack.pop().get_value())
     return traversal
    def dfs(self, data):
        '''
        This function will help us find an node given our elements are not entirely 
        sorted or our method of sorting the data is not exactly clear (we might have 
        a heap). This function will do a depth first search which is similar to a 
        preorder traversal in that we will search Curr L R. This will allow us to 
        search as deep into our tree as quickly as possible. We use the
        stack class in this function. For documentation, go to the stacks folder 
        in the repository.
        INPUT:
            data = Data to be searched for
        OUTPUT:
            Node containing the data given the data exists in the tree, otherwise None
        
        Runtime -- O(n) -- The runtime is proptional to the amount of data in our BST 
        because we might have to search every node before finding the correct node. 
        Average runtime is O(n).
        '''

        stack = Stack.Stack()
        stack.push(self.root)
        while not stack.isEmpty():
            node = stack.pop()
            if data == node.getData():
                return node
            if node.getLeft():
                stack.push(node.getLeft())
            if node.getRight():
                stack.push(node.getRight())
        return None
Exemplo n.º 5
0
    def dfsPrint(self, start):
        if start is None:
            return

        stack = Stack()
        stack.push(start)
        traversal = ""
        while len(stack) > 0:
            traversal += str(stack.peek().value) + "->"

            node = stack.pop()
            if node.left:
                stack.push(node.left)
            if node.right:
                stack.push(node.right)

        return traversal
Exemplo n.º 6
0
    def dfsSize(self):
        if self.root is None:
            return 0

        stack = Stack()
        head = self.root
        if head is not None:
            stack.push(head)
        count = 0

        while len(stack) > 0:
            count += 1
            node = stack.pop()
            if node.left is not None:
                stack.push(node.left)
            if node.right is not None:
                stack.push(node.right)

        return count
Exemplo n.º 7
0
    def reverse_levelorder_print(self, start):
        if start is None:
            return

        queue = Queue()
        stack = Stack()
        queue.enqueue(start)

        traversal = ""
        while len(queue) > 0:
            node = queue.dequeue()

            stack.push(node)

            if node.right:
                queue.enqueue(node.right)
            if node.left:
                queue.enqueue(node.left)

        while len(stack) > 0:
            node = stack.pop()
            traversal += str(node.value) + "-"

        return traversal
Exemplo n.º 8
0
def reverse_k_elements(queue, k):

    stk = Stack.Stack()
    for i in range(0, k):
        stk.push(queue.dequeue().get_data())
    stk.print_stack()
    queue.print_queue()

    while stk.size > 0:
        queue.enqueue(stk.pop().get_data())

    queue.print_queue()

    for i in range(0, queue.size - k):
        queue.enqueue(queue.dequeue().get_data())

    queue.print_queue()
Exemplo n.º 9
0
    def __dfs(self,v):
        '''
        Once we initialize everything (set everything to unexplored), we need a stack
        to help us visit the locations we need. The algorithm looks like this
        1. push the first vertex
        2. Report on it
        3. While !stack.isempty():
            1. pop
            2. Report
            3. Loop through the adjacent vertices
                - Update the edges, mark the vertex as visited (if not yet visited); push
                - If visited, check if edge has been visited, if not mark the edge as a back edge
                    which means we have a cycle

        Remember, graph traversals can have any order we want. It all depends on the
        starting point. In addition, a traversal will automatically create a minimum spanning tree.

        Runtime - O(n + m) - This runtime is a little tricky to derive but I will try my best.
        Since we have to push every single vertex onto the queue at least once, we get O(n). However,
        since we also have to visit every single adjacent vertex to a given vertex, which is equal to
        def(v), we get 2m. We get 2m, by summing up all of the degrees of all of the nodes which we visit.
        This finally gives us a runtime of O(n + 2m) = O(m + n). This is a very good run time because
        we have to visit every single node and edge in this version of a breadth first search (traversal).
        '''

        v.setVisited(True)
        stack = Stack.Stack()
        stack.push(v)
        print(v)
        while not stack.isEmpty():
            vert = stack.pop()
            for adjvert in self.adjacentVertices(vert):
                e = self.areAdjacent(vert, adjvert)
                if not adjvert.getVisited():
                    print(adjvert)
                    adjvert.setVisited(True)
                    e.visited = True
                    e.discovery = True
                    stack.push(adjvert)
                elif not e.visited:
                    self.cycles = True
                    e.visited = True
                    e.discovery = False
def postfixeval(list):
        values = Stack()

        for token in list:
            if token in "0123456789":
                values.push(int(token))

            else:
                if token in "()":
                    continue
                else:
                    op1 = values.pop()
                    op2 = values.pop()
                    result = calculate(token,op1,op2)
                    values.push(result)
        return values.pop()


        print values
Exemplo n.º 11
0
def parChecker(string):
    s=Stack()
    balanced=True
    index=0
    while index<len(string) and balanced:
        symbol=string[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced=False
            else:
                top=s.pop()
                ## we have to see the top that we have removed matches the symbol
                if not matches(top,symbol):
                    balanced=False

        index+=1
    if balanced and s.isEmpty():
        return True
    else:
        return False
Exemplo n.º 12
0
from Stacks import Stack
stack = Stack()


def balanceParen(s):

    opening = set('([{')
    matches = set([('(', ')'), ('[', ']'), ('{', '}')])

    if len(s) % 2 != 0:
        return False

    for paren in s:
        if paren in opening:
            stack.push(paren)
        else:
            if stack.isEmpty():
                return False
            else:
                last_open = stack.pop()

            if (last_open, paren) not in matches:
                return False
    return stack.isEmpty()


p = '{[]'
print(balanceParen(p))
Exemplo n.º 13
0
class Stack(object):

    def __init__(self):
        self.ll = LinkedList()

    def isEmpty(self):
        return self.ll.isEmpty()

    def push(self, data):
        self.ll.addNode(Node(data))

    def pop(self):
        self.ll.delEnd()

    def peek(self):
        return self.ll.returnEndElement()

    def size(self):
        return self.ll.size()


s = Stack()
s.push(133)
s.push(24)
s.push(123)
s.push(12124)

s.pop()
print s.peek()
print s.size()
from Stacks import Stack
def reverse(stack):
    if stack.isEmpty()!=True:
        temp=stack.pop()
        reverse(stack)
        print(temp)
        insert_at_bottom(stack,temp)
def reverse_stack(stack):
    new_stack=Stack()
    while(stack.isEmpty() is not True):
        new_stack.push(stack.pop())
    return new_stack
def insert_at_bottom(stack,element):
    if stack.isEmpty():
        stack.push(element)
    else:
        temp=stack.pop()
        insert_at_bottom(stack,element)
        stack.push(temp)
if __name__=="__main__":
    array=Stack()
    array.push(1)
    array.push(2)
    array.push(3)
    array.push(4)
    array.push(5)
    array.push(6)
    array.print_stack()
    reverse(array)
    array.print_stack()
def reverse_stack(stack):
    new_stack=Stack()
    while(stack.isEmpty() is not True):
        new_stack.push(stack.pop())
    return new_stack
Exemplo n.º 16
0
Arquivo: 3.4.py Projeto: susnchen/CtCI
class MyQueue:
    def __init__(self):
        self.stack1 = Stack(0)
        self.stack2 = Stack(0)
        self.stack1.pop()
        self.stack2.pop()
        self.use1 = True

    def add(self, value):
        if self.use1:
            self.stack1.push(value)
        else:
            self.stack2.push(value)

    def remove(self):
        if self.use1:
            self.use1 = not self.use1
            while (not self.stack1.isEmpty()):
                self.stack2.push(self.stack1.pop())
            return self.stack2.pop()
        else:
            self.use1 = not self.use1
            while (not self.stack2.isEmpty()):
                self.stack1.push(self.stack2.pop())
            return self.stack1.pop()
Exemplo n.º 17
0
    while stk.size > 0:

        m = stk.pop().get_data()
        n = None
        if stk.size > 0:
            n = stk.pop().get_data()

            if abs(n - m) != 1:
                pairwise_sorted = False
                break
        result[m] = n

    return pairwise_sorted, result


def create_stack(Ar, stk):
    for elem in Ar:
        stk.push(elem)
    return stk


Ar = [4, 5, -2, -3, 11, 10, 5, 6, 20]
stk = Stack.Stack()
stk = create_stack(Ar, stk)
print "Orig stack: "
stk.print_stack()
pairwise_sorted, result = is_pairwise_sorted(stk)
print "is_pairwise_sorted: " + str(pairwise_sorted)
print "pairs: " + str(result)
Exemplo n.º 18
0
Arquivo: 3.4.py Projeto: susnchen/CtCI
 def __init__(self):
     self.stack1 = Stack(0)
     self.stack2 = Stack(0)
     self.stack1.pop()
     self.stack2.pop()
     self.use1 = True