def test_array_stack(): array_stack = ArrayStack() # Assert that we start with an empty stack assert array_stack.is_empty() with pytest.raises(Empty): array_stack.top() # Push a bunch of elements onto the stack for i in range(10): array_stack.push(i) array_stack, top = array_stack.top() assert top == i assert len(array_stack) == i + 1 # Pop all the elements off for i in range(len(array_stack) - 1, -1, -1): array_stack, val = array_stack.pop() assert val == i assert len(array_stack) == i # Assert we are back to an empty stack assert array_stack.is_empty() with pytest.raises(Empty): array_stack.pop()
def match_paranthesis(paranthesis): left = '{[(|' right = '}])|' stack = ArrayStack() for s in paranthesis: if s in left and s not in right: stack.push(s) if s in right: if s not in left: if stack.is_empty(): return False else: if right.index(s) == left.index(stack.top()): stack.pop() else: return False else: if stack.is_empty(): stack.push(s) else: if s != stack.top(): stack.push(s) else: stack.pop() return stack.is_empty()
def infix_to_postfix(expression): postfix = [] priority = {'(': 1, '+': 2, '-': 2, '*': 3, '/': 3, '^': 4} operators = ArrayStack() for token in expression: if token in OPERATORS: # Operators are added to the stack, but first the ones with a # higher priority are added to the result: while not operators.is_empty() and priority[token] <= priority[ operators.top()]: postfix.append(operators.pop()) operators.push(token) # Left parenthesis are added to the stack: elif token == '(': operators.push(token) # Operators between parenthesis are added from the stack to the result: elif token == ')': while operators.top() != '(': postfix.append(operators.pop()) operators.pop() # Pop the left parentheses from the stack. # Operands are added to the result: else: postfix.append(token) while not operators.is_empty(): # The remaining operators are added from the stack to the result: postfix.append(operators.pop()) return postfix
def is_valid_html(raw_html): """ Return True if the each opening html tag in the raw_html string has and associated closing html tag. Parameters ---------- raw_html: str or unicode The raw html string we need to check for validity Returns ------- Boolean """ def is_opening_tag(tag): return not tag.startswith('/') stack = ArrayStack() opening_idx = raw_html.find('<') while opening_idx != -1: closing_idx = raw_html.find('>', opening_idx + 1) if closing_idx == -1: return False tag = raw_html[opening_idx + 1:closing_idx] if is_opening_tag(tag): stack.push(tag) else: if stack.is_empty() or stack.top() != tag[1:]: return False else: stack.pop() opening_idx = raw_html.find('<', closing_idx + 1) return stack.is_empty()
def cal_simple_expression(exp): """只有+-*/四种运算, 运算数为整数, 运算符前后有空格.""" end = '$' # 表达式结束标志, 最低优先级 priority = {end: 0, '+': 1, '-': 1, '*': 2, '/': 2} operator_func = {'+': add, '-': sub, '*': mul, '/': truediv} operand = ArrayStack() operator = ArrayStack() exp = exp.split() exp.append(end) # 添加表达式结束标志以计算最终结果 i = 0 while i < len(exp): e = exp[i] if e not in priority.keys(): operand.push(int(e)) i += 1 else: # 高优先级运算符直接push if operator.is_empty() or priority[e] > priority[operator.top()]: operator.push(e) i += 1 # 低优先级运算符在下一次循环时处理 else: func = operator_func[operator.pop()] num1 = operand.pop() num2 = operand.pop() operand.push(func(num2, num1)) return operand.pop()
def is_matching(expr): """ Return True if delimiters in expr match correctly, False otherwise Parameters ---------- test_str: str or unicode expression to evaluate parameters correctness Returns ------- Boolean """ delimiters_map = {'(': ')', '{': '}', '[': ']'} stack = ArrayStack() for c in expr: if c in delimiters_map: stack.push(c) elif c in delimiters_map.itervalues(): if stack.is_empty() or delimiters_map[stack.top()] != c: return False else: stack.pop() return stack.is_empty()
def test_stack(self): stack = ArrayStack() assert stack.__repr__() == 'Stack: bottom [] top' assert stack.is_empty() == True stack.push(1) assert stack.is_empty() == False assert stack.__repr__() == 'Stack: bottom [1] top' stack.push(2) assert len(stack) == 2 assert stack.__repr__() == 'Stack: bottom [1,2] top' assert stack.top() == 2 assert stack.pop() == 2 assert len(stack) == 1 assert stack.__repr__() == 'Stack: bottom [1] top' assert stack.top() == 1 assert stack.pop() == 1 assert stack.__repr__() == 'Stack: bottom [] top' with pytest.raises(EmptyError): stack.top() with pytest.raises(EmptyError): stack.pop()
def main(): print("Creating a stack...") a = ArrayStack() print("Length of the stack:", len(a)) print("The stack is empty:", a.is_empty()) print() print("Pushing 10 to the stack...") a.push(10) print("The element at the top of the stack is", a.top()) print("Length of the stack:", len(a)) print("The stack is empty:", a.is_empty()) print() print("Pushing 20 30 40 50 to the stack in this order...") a.push(20) a.push(30) a.push(40) a.push(50) print("The element at the top of the stack is", a.top()) print("Length of the stack:", len(a)) print("The stack is empty:", a.is_empty()) print() print("Popping the stack...") a.pop() print("The element at the top of the stack is", a.top()) print("Length of the stack:", len(a)) print("The stack is empty:", a.is_empty()) print() print("Popping the stack 4 times...") for i in range(3): a.pop() print("The element at the top of the stack is", a.top()) print("Length of the stack:", len(a)) print("The stack is empty:", a.is_empty()) print()
from array_stack import ArrayStack a = '((()(){([()])}))' cd = '((({{}})))' b= '()(()){([()])}' c=')(()){([()])}' d='(}' S=ArrayStack() list_a = [] for i in a: if i=='(' or i=='{' or i=='[': S.push(i) print("1",S.data) elif i==')' and S.top()=='(': S.pop() print("2",S.data) elif i=='}' and S.top()=='{': S.pop() print("3",S.data) elif i==']' and S.top()=='[': S.pop() print("4",S.data) print(S.is_empty())
from array_stack import ArrayStack a = '((()(){([()])}))' cd = '((({{}})))' b = '()(()){([()])}' c = ')(()){([()])}' d = '(}' S = ArrayStack() list_a = [] for i in a: if i == '(' or i == '{' or i == '[': S.push(i) print("1", S.data) elif i == ')' and S.top() == '(': S.pop() print("2", S.data) elif i == '}' and S.top() == '{': S.pop() print("3", S.data) elif i == ']' and S.top() == '[': S.pop() print("4", S.data) print(S.is_empty())