Example #1
0
def move_disks(n: int, destination: Stack, buffer: Stack, origin: Stack):

    if n > 0:
        move_disks(n-1, buffer, destination, origin)
        print('{} -> {}'.format(origin.stack_nr, destination.stack_nr))
        destination.push(origin.pop())
        move_disks(n-1, destination, origin, buffer)
Example #2
0
def move_disks(n: int, destination: Stack, buffer: Stack, origin: Stack):

    if n > 0:
        move_disks(n - 1, buffer, destination, origin)
        print('{} -> {}'.format(origin.stack_nr, destination.stack_nr))
        destination.push(origin.pop())
        move_disks(n - 1, destination, origin, buffer)
Example #3
0
class CustomStack(Stack):
    def __init__(self):
        super().__init__()

        self.min_stack = Stack()

    def push(self, value):

        # Keep track of the min value
        if self.min_stack.is_empty() or self.min_stack.peek() >= value:
            self.min_stack.push(value)

        super().push(value)

    def pop(self):

        value = super().pop()

        if value == self.min_stack.peek():
            self.min_stack.pop()

        return value

    def get_minimum(self):
        if not self.min_stack.is_empty():
            return self.min_stack.peek()
Example #4
0
class CustomStack(Stack):

    def __init__(self):
        super().__init__()

        self.min_stack = Stack()

    def push(self, value):

        # Keep track of the min value
        if self.min_stack.is_empty() or self.min_stack.peek() >= value:
            self.min_stack.push(value)

        super().push(value)

    def pop(self):

        value = super().pop()

        if value == self.min_stack.peek():
            self.min_stack.pop()

        return value

    def get_minimum(self):
        if not self.min_stack.is_empty():
            return self.min_stack.peek()
Example #5
0
    def test_question_6(self):
        stack = Stack()
        numbers = []
        for i in range(10):
            random_number = random.randint(0, 100)
            stack.push(random_number)
            numbers.append(random_number)

        sort_stack(stack)

        for i in sorted(numbers):
            assert i == stack.pop()
Example #6
0
    def consolidate(self):
        """
        Restructure the tree back to a binomial tree
        """
        trees_by_rank = {}
        tree_stack = Stack()

        for tree in self.trees:
            tree_stack.push(tree)

        # Iterate over the trees and merge trees of the same rank
        while not tree_stack.is_empty():
            tree = tree_stack.pop()

            if tree is None:
                continue

            if tree.rank in trees_by_rank:
                existing_tree = trees_by_rank[tree.rank]
                del trees_by_rank[tree.rank]
                tree_stack.push(tree.merge_min(existing_tree))

            else:
                trees_by_rank[tree.rank] = tree

        # Build a new tree list and find the new min node
        new_trees = trees_by_rank.values()
        self.trees = LinkedList()
        self.min_tree = None

        for new_tree in new_trees:
            self.trees.append(new_tree)
            if self.min_tree is None or self.min_tree.value.value > new_tree.value:
                self.min_tree = self.trees.get_tail_node()
Example #7
0
    def consolidate(self):
        """
        Restructure the tree back to a binomial tree
        """
        trees_by_rank = {}
        tree_stack = Stack()

        for tree in self.trees:
            tree_stack.push(tree)

        # Iterate over the trees and merge trees of the same rank
        while not tree_stack.is_empty():
            tree = tree_stack.pop()

            if tree is None:
                continue

            if tree.rank in trees_by_rank:
                existing_tree = trees_by_rank[tree.rank]
                del trees_by_rank[tree.rank]
                tree_stack.push(tree.merge_min(existing_tree))

            else:
                trees_by_rank[tree.rank] = tree

        # Build a new tree list and find the new min node
        new_trees = trees_by_rank.values()
        self.trees = LinkedList()
        self.min_tree = None

        for new_tree in new_trees:
            self.trees.append(new_tree)
            if self.min_tree is None or self.min_tree.value.value > new_tree.value:
                self.min_tree = self.trees.get_tail_node()
Example #8
0
def infix_to_postfix(expression):
    operator_stack = Stack()

    precedence_rules = {
        '/': 3,
        '*': 3,
        '+': 2,
        '-': 2,
        '%': 1,
        '(': 1
    }

    output_list = []

    for char in expression:

        if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789':
            output_list.append(char)

        elif char == '(':
            operator_stack.push('(')

        elif char == ')':
            current_char = operator_stack.pop()
            while current_char != '(':
                output_list.append(current_char)
                current_char = operator_stack.pop()

        elif char == ' ':
            pass

        elif char in precedence_rules.keys():
            while len(operator_stack) > 0 and precedence_rules[operator_stack.peek()] >= precedence_rules[char]:
                output_list.append(operator_stack.pop())

            operator_stack.push(char)

    while len(operator_stack):
        output_list.append(operator_stack.pop())

    return ' '.join(output_list) 
Example #9
0
def hanoi(n):

    start_stack = Stack()
    start_stack.stack_nr = 1
    for i in reversed(range(n)):
        start_stack.push(i)

    buffer = Stack()
    buffer.stack_nr = 2

    destination = Stack()
    destination.stack_nr = 3

    move_disks(n, destination, buffer, start_stack)
Example #10
0
    def test_stack(self):
        stack = Stack()

        stack.push(5)

        assert len(stack) == 1

        stack.push(2)

        assert len(stack) == 2

        assert stack.peek() == 2

        assert stack.pop() == 2

        assert stack.pop() == 5

        assert_raises(IndexError, stack.pop)
Example #11
0
    def test_stack(self):
        stack = Stack()

        stack.push(5)

        assert len(stack) == 1

        stack.push(2)

        assert len(stack) == 2

        assert stack.peek() == 2

        assert stack.pop() == 2

        assert stack.pop() == 5

        assert_raises(IndexError, stack.pop)
Example #12
0
def sort_stack(stack: Stack):

    extra_stack = Stack()

    while not stack.is_empty():

        element = stack.pop()

        elements_transfered = 0
        while not extra_stack.is_empty() and extra_stack.peek() > element:
            elements_transfered += 1
            stack.push(extra_stack.pop())

        extra_stack.push(element)

        for _ in range(elements_transfered):
            extra_stack.push(stack.pop())

    while not extra_stack.is_empty():
        stack.push(extra_stack.pop())
Example #13
0
def hanoi(n):

    start_stack = Stack()
    start_stack.stack_nr = 1
    for i in reversed(range(n)):
        start_stack.push(i)

    buffer = Stack()
    buffer.stack_nr = 2

    destination = Stack()
    destination.stack_nr = 3

    move_disks(n, destination, buffer, start_stack)
Example #14
0
def graham(points: List) -> List:
    """
    Graham's scan is a method of finding the convex hull of a finite
    set of points in the plane with time complexity O(n log n).
    It is named after Ronald Graham, who published the original
    algorithm in 1972.The algorithm finds all vertices of the
    convex hull ordered along its boundary.
    """

    # Find the bottom left point and remove it from the set
    bottom_left_point = min(points, key=lambda x: (x[1], x[0]))

    # Put the points on a min heap by polar angle
    polar_points = [(get_polar_angle(bottom_left_point, x), x) for x in points
                    if x != bottom_left_point]
    point_heap = BinomialHeap(polar_points)

    # Push the first 3 elements on a stack
    stack = Stack()
    stack.push(bottom_left_point)
    stack.push(point_heap.pop()[1])
    stack.push(point_heap.pop()[1])

    for _ in range(len(point_heap)):
        _, p3 = point_heap.pop()
        while is_counterclockwise(stack.peek(1), stack.peek(), p3) < 0:
            stack.pop()
        stack.push(p3)

    return stack.to_array()
Example #15
0
class CustomQueue():
    def __init__(self):
        self.enqueue_stack = Stack()
        self.dequeue_stack = Stack()

    def enqueue(self, value):
        while not self.dequeue_stack.is_empty():
            self.enqueue_stack.push(self.dequeue_stack.pop())

        return self.enqueue_stack.push(value)

    def dequeue(self):
        while not self.enqueue_stack.is_empty():
            self.dequeue_stack.push(self.enqueue_stack.pop())
        return self.dequeue_stack.pop()

    def is_empty(self):
        return not self.enqueue_stack.size() and not self.dequeue_stack.size()
Example #16
0
def graham(points: List) -> List:
    """
    Graham's scan is a method of finding the convex hull of a finite
    set of points in the plane with time complexity O(n log n).
    It is named after Ronald Graham, who published the original
    algorithm in 1972.The algorithm finds all vertices of the
    convex hull ordered along its boundary.
    """

    # Find the bottom left point and remove it from the set
    bottom_left_point = min(points, key=lambda x: (x[1], x[0]))

    # Put the points on a min heap by polar angle
    polar_points = [(get_polar_angle(bottom_left_point, x), x) for x in points if x != bottom_left_point]
    point_heap = BinomialHeap(polar_points)

    # Push the first 3 elements on a stack
    stack = Stack()
    stack.push(bottom_left_point)
    stack.push(point_heap.pop()[1])
    stack.push(point_heap.pop()[1])

    for _ in range(len(point_heap)):
        _, p3 = point_heap.pop()
        while is_counterclockwise(stack.peek(1), stack.peek(), p3) < 0:
            stack.pop()
        stack.push(p3)

    return stack.to_array()
Example #17
0
def infix_to_postfix(expression):
    operator_stack = Stack()

    precedence_rules = {'/': 3, '*': 3, '+': 2, '-': 2, '%': 1, '(': 1}

    output_list = []

    for char in expression:

        if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789':
            output_list.append(char)

        elif char == '(':
            operator_stack.push('(')

        elif char == ')':
            current_char = operator_stack.pop()
            while current_char != '(':
                output_list.append(current_char)
                current_char = operator_stack.pop()

        elif char == ' ':
            pass

        elif char in precedence_rules.keys():
            while len(operator_stack) > 0 and precedence_rules[
                    operator_stack.peek()] >= precedence_rules[char]:
                output_list.append(operator_stack.pop())

            operator_stack.push(char)

    while len(operator_stack):
        output_list.append(operator_stack.pop())

    return ' '.join(output_list)
Example #18
0
class CustomQueue():

    def __init__(self):
        self.enqueue_stack = Stack()
        self.dequeue_stack = Stack()

    def enqueue(self, value):
        while not self.dequeue_stack.is_empty():
            self.enqueue_stack.push(self.dequeue_stack.pop())

        return self.enqueue_stack.push(value)

    def dequeue(self):
        while not self.enqueue_stack.is_empty():
            self.dequeue_stack.push(self.enqueue_stack.pop())
        return self.dequeue_stack.pop()

    def is_empty(self):
        return not self.enqueue_stack.size() and not self.dequeue_stack.size()
Example #19
0
    def push(self, value):
        if self.stacks[-1].size() == self.max_size:
            self.stacks.append(Stack())

        self.stacks[-1].push(value)
Example #20
0
 def __init__(self, max_size=10):
     self.stacks = [Stack()]
     self.max_size = max_size
Example #21
0
    def __init__(self):
        super().__init__()

        self.min_stack = Stack()
Example #22
0
 def __init__(self):
     self.enqueue_stack = Stack()
     self.dequeue_stack = Stack()
Example #23
0
 def __init__(self):
     self.enqueue_stack = Stack()
     self.dequeue_stack = Stack()
Example #24
0
    def __init__(self):
        super().__init__()

        self.min_stack = Stack()