class TestStack(unittest.TestCase):
    def setUp(self):
        self._stack = Stack()

    def test_pop_from_empty_stack_raises_index_error(self):
        self.assertRaises(IndexError, self._stack.pop)

    def test_pop_from_empty_stack_which_had_items_raises_index_error(self):
        self._stack.push(1)
        self._stack.pop()
        self.assertRaises(IndexError, self._stack.pop)

    def test_pop_returns_items_in_order(self):
        self._stack.push(3)
        self._stack.push(2)
        self._stack.push(1)
        assert (self._stack.pop() == 1)
        assert (self._stack.pop() == 2)
        assert (self._stack.pop() == 3)

    def test_peek_returns_top_item(self):
        self._stack.push(2)
        self._stack.push(1)
        assert (self._stack.peek() == 1)

    def test_peek_leaves_item_on_stack(self):
        self._stack.push(1)
        assert (self._stack.peek() == 1)
        assert (self._stack.pop() == 1)
示例#2
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
示例#3
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))
示例#4
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
示例#5
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__()
示例#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)
示例#7
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())
示例#8
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")
示例#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
示例#10
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))
示例#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
示例#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
示例#13
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))
示例#14
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())
示例#15
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
示例#16
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
示例#17
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))
示例#18
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
示例#19
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
示例#20
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
示例#21
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
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
示例#23
0
def calculator(equation):
    error = "算式不合法"
    number_stack = Stack()
    action_stack = Stack()

    equation = reform_equation(equation)
    equations = make_equations(equation)

    def do_cal():
        one = number_stack.pop()
        two = number_stack.pop()

        res = 0
        action = action_stack.pop()
        if action == '*':
            res = two * one
        if action == '-':
            res = two - one
        if action == '+':
            res = two + one
        if action == '/':
            res = two / one

        number_stack.push(res)

    def got_number(number):
        number_stack.push(number)

    def got_action(action):
        # 非常复杂
        if action == ')':
            # 直到遇到 '(' 才停止计算,遇不到则报错
            while action_stack.last() is not '(':
                do_cal()
            action_stack.pop()
            return
        if action == '(' or action_stack.if_empty(
        ) or action_weight(action) > action_weight(action_stack.last()):
            action_stack.push(action)
            return

        do_cal()
        action_stack.push(action)

    while len(equations) is not 0:
        item = equations.pop()
        if item in ['*', '-', '(', '+', ')', '/']:
            try:
                got_action(item)
            except IndexError:
                return error
            except ZeroDivisionError:
                return '错误,除数出现 0'
            except Exception as E:
                return str(E)
        else:
            try:
                got_number(float(item))
            except ValueError:
                return error

    # 把列表中的内容全部弹出,返回最后一个数
    while action_stack.len() > 0:
        try:
            do_cal()
        except IndexError:
            return error
        except ZeroDivisionError:
            return '错误,除数出现'

    if number_stack.len() is not 1:
        return error
    return number_stack.pop()
示例#24
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())
示例#25
0
def test_stack_push(given, expected):
    stack = Stack(given)
    assert stack.pop().value == given[-1]
    assert stack.__str__() == expected
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)

    if i == brackets_dict.get(closed_brackets_stack.end_stack_pop()):
        i = open_brackets_stack.pop()
        continue
    else:
        print("baasa")
        exit()