Example #1
0
def construct_parse_tree(expression):
    operators = ['(', ')', '+', '-', '*', '/']
    # expr_list = expression.split()
    parse_tree = BinaryTree(None)
    current_tree = parse_tree
    path = Stack()
    path.push(parse_tree)
    for token in expression:
        if token == '(':
            current_tree.insert_left(' ')
            path.push(current_tree)
            current_tree = current_tree.get_left()
        elif token not in operators:
            try:
                current_tree.set_root(int(token))
                current_tree = path.pop()
            except ValueError:
                raise ValueError("Token '{0}' is not a valid integer".format(token))
        elif token == ')':
            current_tree = path.pop()
        elif token in operators:
            current_tree.set_root(token)
            path.push(current_tree)
            current_tree.insert_right(' ')
            current_tree = current_tree.get_right()

    return parse_tree
Example #2
0
def generate_workout(n: int):

    pyramid = Stack()
    data_file = open("generator/data.json")
    data = json.load(data_file)

    #apilando
    start_stack = time.perf_counter()

    for i in range(n):
        exercise = random.choice(data["random_exercises"])
        pyramid.push(exercise)

        if (i % 10000 == 0):
            print("batch", i)

    end_stack = time.perf_counter()

    #desapilando

    start_unstack = time.perf_counter()
    while (pyramid.size > 0):
        current_exercise = pyramid.pop()

        if (pyramid.size % 10000 == 0):
            print("se han desapilado: ", (n - pyramid.size))

    end_unstack = time.perf_counter()

    print(f"Stack time in {end_stack-start_stack:0.4f} seconds")
    print(f"Unstack time in {end_unstack-start_unstack:0.4f} seconds")
Example #3
0
def check_parentheses(symbol_string):
    s = Stack()
    balanced = True
    index = 0
    matcher = {
        '}': '{',
        ']': '[',
        ')': '(',
    }
    while index < len(symbol_string) and balanced:
        symbol = symbol_string[index]
        if symbol in ['(', '[', '{']:
            s.push(symbol)
        elif symbol in [')', ']', '}']:
            if s.is_empty() or matcher[symbol] != s.peek():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.is_empty():
        return True
    else:
        return False
Example #4
0
class MaxStack(Stack):
    def __init__(self) -> None:
        super().__init__()
        self.max_stack = Stack()

    def peek(self):
        return super().peek()

    def push(self, item: Any):
        if self.max_stack.empty():
            self.max_stack.push(item)
        else:
            self.max_stack.push(max(item, self.max_stack.peek()))
        super().push(item)

    def pop(self):
        self.max_stack.pop()
        return super().pop()

    def max(self):
        """
        Получить максимальный элемент. Не извлекает его из стека.
        """
        return self.max_stack.peek()

    def empty(self):
        return super().empty()

    def __len__(self):
        return super().__len__()

    def __bool__(self):
        return super().__bool__()
Example #5
0
def top_sort(adj_list):
    n = len(adj_list)
    colors = ['w'] * n
    stack = Stack()

    for i0 in range(n):
        is_cycle = dfs_colored_step(i0, adj_list, colors, stack)

        if is_cycle:
            raise ValueError('Cycle was found')

    ii_order = stack.to_list()
    return ii_order
Example #6
0
 def test_pop(self):
     a = Stack()
     a.push(5)
     self.assertEqual(a.pop(), 5)
     a.push(4)
     a.push(8)
     self.assertEqual(a.pop(), 8)
     self.assertEqual(a.pop(), 4)
Example #7
0
def find_linked_components(adj_list):
    # only for nonor graphs
    n = len(adj_list)
    colors = ['w'] * n
    components = []

    for i0 in range(n):

        stack = Stack()
        dfs_colored_step(i0, adj_list, colors, stack)
        component = set(stack.to_list())

        if component:
            components.append(component)

    return components
Example #8
0
def quick_sort_iterative(x):
    i_left, i_right = 0, len(x) - 1

    stack = Stack()
    stack.push((i_left, i_right))

    while stack:

        i_left, i_right = stack.pop()

        if i_right <= i_left:
            continue

        i, j = partitioning(x, i_left, i_right)

        stack.push((i_left, j))
        stack.push((i, i_right))
Example #9
0
def test_pop():
    my_stack = Stack()
    my_stack.push(0)
    my_stack.push(1)
    popped = my_stack.pop()
    assert popped == 1
    assert my_stack.peek() == 0
Example #10
0
def test_push():
    my_stack = Stack()
    my_stack.push(0)
    my_stack.push(1)
    assert my_stack.items == [0, 1]
    assert my_stack.size() == 2
    assert my_stack.is_empty() is False
Example #11
0
def convert_decimal_to_binary(decimal_number):
    s = Stack()
    while decimal_number > 0:
        s.push(decimal_number % 2)
        decimal_number = decimal_number // 2

    num = ""
    while not s.is_empty():
        num = num + str(s.pop())

    return num
Example #12
0
def convert_decimal_to_base(decimal_number, base):
    digits = "0123456789ABCDE"
    s = Stack()
    while decimal_number > 0:
        s.push(decimal_number % base)
        decimal_number = decimal_number // base

    num = ""
    while not s.is_empty():
        num = num + digits[s.pop()]

    return num
Example #13
0
def evaluate_postfix_expr(post_expr):
    expr = post_expr.split(' ')
    operands = Stack()
    ops = '+-/*'

    for token in expr:
        if token not in ops:
            operands.push(token)
        else:
            second_operand = operands.pop()
            first_operand = operands.pop()
            result = 0
            if token == '+':
                result = int(first_operand) + int(second_operand)
            elif token == '-':
                result = int(first_operand) - int(second_operand)
            elif token == '*':
                result = int(first_operand) * int(second_operand)
            elif token == '/':
                result = int(first_operand) / int(second_operand)
            operands.push(result)

    print(operands.pop())
Example #14
0
def resolve(s: str):
    stack = Stack()
    first_open_pos = 0
    open_brackets, close_brackets = ['(', '[', '{'], [')', ']', '}']
    for i, ch in enumerate(s, 1):
        if ch in open_brackets:
            if stack.empty():
                first_open_pos = i
            stack.push(ch)
        else:
            if stack.empty():
                return i
            else:
                opened = stack.pop()
                if open_brackets.index(opened) != close_brackets.index(ch):
                    return i
    if stack.empty():
        return 'Success'
    else:
        return first_open_pos
Example #15
0
def find_iterative(lst: List[int]) -> int:
    """
    Ищет высоту дерева. Итеративный алгоритм без построения дерева.
    Имеет сложность О(n^2).
    """
    root_value, root_depth = lst.index(-1), 1
    max_depth = 1
    tasks = Stack()
    tasks.push((root_value, root_depth))
    while tasks:
        v = tasks.pop()
        value, depth = v[0], v[1]
        if max_depth < depth:
            max_depth = depth
        for i in range(len(lst)):
            if lst[i] == value:
                tasks.push((i, depth + 1))
    return max_depth
Example #16
0
def check_parentheses_bk(symbol_string):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbol_string) and balanced:
        symbol = symbol_string[index]
        if symbol in '{[(':
            s.push(symbol)
        elif symbol in ')]}':
            if s.is_empty() or not matches(s.pop(), symbol):
                balanced = False

        index = index + 1

    if balanced and s.is_empty():
        return True
    else:
        return False
Example #17
0
def find_iterative_building_tree(lst: List[int]) -> int:
    """
    Ищет высоту дерева. Итеративный алгоритм с постоением дерева. Сложность
    алгоритма О(n).
    """
    root = build_tree(lst)
    root.level = 1

    max_level = 1
    tasks = Stack()
    tasks.push(root)
    while tasks:
        node = tasks.pop()
        if max_level < node.level:
            max_level = node.level
        for child in node.children:
            child.level = node.level + 1
            tasks.push(child)
    return max_level
Example #18
0
def parens_matched(x):
    # Read a string from left to right and decide whether left and right parentheses are balanced.

    stack = Stack()
    matched = True

    for char in x:
        if char == '(':
            stack.push(0)
        elif char == ')':
            popped = stack.pop()
            if popped == []:
                matched = False
                break

    return matched and stack.size() == 0
Example #19
0
def dec_to_binary(x):
    # Return binary representation of base 10 (decimal) number.

    exponents = Stack()

    while x > 0:
        remainder = x % 2
        exponents.push(remainder)
        x = x // 2

    binary = ''

    while not exponents.is_empty():
        binary += str(exponents.pop())

    return binary
Example #20
0
    def __init__(self,
                 ID,
                 date,
                 timeslot,
                 theater,
                 film,
                 freeplaces=None,
                 tickets=None):
        self.ID = ID
        self.date = date
        self.timeslot = timeslot
        self.fulldate = datetime.datetime(date.year, date.month, date.day,
                                          timeslot.hour, timeslot.minute)
        self.theater = theater
        self.film = film
        if freeplaces == None:
            freeplaces = theater.places
        self.freeplaces = freeplaces
        # this number is managed by the 'parent' cinema

        if tickets == None:
            tickets = Stack()
        self.tickets = tickets
def validate_html_tags(html_code: str):
    tags = Stack()
    balanced = True
    start_index = int(html_code.find('<')) + 1
    end_index = int(html_code.find('>'))

    while balanced and start_index > 0 and end_index > 0:
        tag = html_code[start_index:end_index]
        # print("start -> {} , End -> {} ; Tag -> {}".format(str(start_index), str(end_index), tag))
        if not tag.startswith('/'):
            tags.push(tag)
        else:
            if tags.is_empty():
                balanced = False
                break
            peek_tag = '/' + tags.pop()
            if peek_tag != tag:
                balanced = False

        start_index = int(html_code.find('<', end_index)) + 1
        end_index = int(html_code.find('>', start_index))

    return balanced
Example #22
0
 def test_isEmpty(self):
     a = Stack()
     self.assertTrue(a.isEmpty())
     a.push(5)
     self.assertFalse(a.isEmpty())
     a.push(5)
     self.assertFalse(a.isEmpty())
     a.pop()
     a.pop()
     self.assertTrue(a.isEmpty())
Example #23
0
 def test_push(self):
     a = Stack()
     self.assertTrue(a.push(4))
     self.assertTrue(a.push(6))
     self.assertTrue(a.push("foo"))
Example #24
0
 def test_top(self):
     a = Stack()
     a.push(5)
     self.assertEqual(a.top(), 5)
     a.push(9)
     self.assertEqual(a.top(), 9)
     a.push("foo")
     self.assertEqual(a.top(), "foo")
Example #25
0
 def __init__(self) -> None:
     super().__init__()
     self.max_stack = Stack()
Example #26
0
def convert_infix_to_prefix(infix_expression):
    reverse = reverse_string(infix_expression)
    operators = Stack()
    prefix_expr = []
    ops = '(+-*/**)'
    expr_list = list(reverse)

    for token in expr_list:
        if token not in ops:
            prefix_expr.append(token)
        elif token == ')':
            operators.push(token)
        elif token == '(':
            while operators.peek() != ')':
                prefix_expr.append(operators.pop())
            operators.pop()
        else:
            while (not operators.is_empty()
                   ) and precedence[operators.peek()] > precedence[token]:
                prefix_expr.append(operators.pop())
            operators.push(token)

    while not operators.is_empty():
        prefix_expr.append(operators.pop())

    return reverse_string(''.join(prefix_expr))
Example #27
0
from structures.linkedList import List
from structures.queue import Queue
from structures.stack import Stack

mylist = List()

for i in range(5):
    mylist.add(i)

mylist.add(5)
mylist.add(7, 1)

for i in mylist:
    print(i)

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
for i in range(queue.size):
    print(queue.dequeue())

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
for i in range(stack.size):
    print(stack.pop())
Example #28
0
def convert_infix_to_postfix(infix_expr):
    op = Stack()
    postfix = []
    infix = list(infix_expr)
    for index in range(len(infix)):
        if infix[index] in ops:
            while (not op.is_empty()) and precedence[op.peek()] >= precedence[infix[index]]:
                if op.peek() == '(':
                    op.pop()
                else:
                    postfix.append(op.pop())
            if infix[index] != ')':
                op.push(infix[index])
        elif infix[index] != ' ':
            postfix.append(infix[index])

    while op.size() > 0:
        postfix.append(op.pop())

    print(''.join(postfix))
Example #29
0
def convert_infix_to_postfix_new(infix_expr):
    op = Stack()
    postfix = []
    infix = list(infix_expr)
    for index in range(len(infix)):
        token = infix[index]
        if token not in ops:
            postfix.append(token)
        elif token == '(':
            op.push(token)
        elif token == ')':
            while op.peek() != '(':
                postfix.append(op.pop())
            op.pop()
        else:
            while (not op.is_empty()) and precedence[op.peek()] >= precedence[infix[index]]:
                postfix.append(op.pop())
            op.push(token)

    while not op.is_empty():
        postfix.append(op.pop())

    print(''.join(postfix))
from structures.stack import Stack

open_brackets = ["{", "[", "("]
closed_brackets = ["}", "]", ")"]
brackets_dict = {"{": "}", "[": "]", "(": ")"}

brackets = "{[]}"
open_brackets_stack = Stack()
closed_brackets_stack = Stack()

# before starting lets verify that brackets are even
if len(brackets) % 2 != 0:
    print("baasa")
    exit()

for i in brackets:
    if i in open_brackets:
        open_brackets_stack.push(i)
    else:
        closed_brackets_stack.push(i)

# lets verify that there is the same amount of open and close brackets
if open_brackets_stack.__sizeof__() != closed_brackets_stack.__sizeof__():
    print("baasa")
    exit()

i = open_brackets_stack.pop()
# check if brackets from open eq closed barckets end pop represented in brackets_dict
while i:

    barckets_dict_pop = brackets_dict.get(i)