def test_stack_array2(self): stack = StackArray() for i in range(3): stack.push(i) self.assertEqual(stack.size(), 3) self.assertFalse(stack.is_empty()) self.assertEqual(stack.peek(), 2)
def infix_to_postfix(infixexpr): """Converts an infix expression to an equivalent postfix expression """ """Signature: a string containing an infix expression where tokens are space separated is the single input parameter and returns a string containing a postfix expression where tokens are space separated""" s = StackArray(30) postfixList = [] tokenList = infixexpr.split() prec = {'^':4, '/':3, '*':3, '+':2, '-':2, '(':1} for t in tokenList: if t in "0123456789": postfixList.append(t) elif t == "(": s.push(t) elif t ==")": topt = s.pop() while topt != "(": postfixList.append(topt) topt = s.pop() else: while (not s.is_empty()) and \ (prec[s.peek()] >= prec[t]): postfixList.append(s.pop()) s.push(t) while not s.is_empty(): postfixList.append(s.pop()) return " ".join(postfixList)
def test_stack_array4(self): stack = StackArray() for i in range(10): stack.push(i) for i in range(10): val = stack.pop() self.assertRaises(IndexError, stack.pop) self.assertRaises(IndexError, stack.peek)
def test_stack_array5(self): stack = StackArray() for i in range(3): stack.push(i) val = stack.pop() stack.push(val) self.assertEqual(stack.pop(), 2) self.assertEqual(stack.peek(), 1) self.assertEqual(stack.pop(), 1)
def test_pop(self): stk_a = StackArray(4) with self.assertRaises(IndexError): stk_a.pop() stk_a.push(6) stk_a.push(7) stk_a.push(9) self.assertEqual(stk_a.pop(), 9) self.assertEqual(stk_a.pop(), 7) self.assertEqual(stk_a.pop(), 6)
def test_stack_array3(self): stack = StackArray() for i in range(3): stack.push(i) self.assertEqual(stack.size(), 3) self.assertFalse(stack.is_empty()) self.assertEqual(stack.pop(), 2) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.pop(), 0) self.assertEqual(stack.size(), 0) self.assertTrue(stack.is_empty())
def test_push(self): stack_1a = StackArray() stack_1a.push(7) stack_2a = StackArray() stack_2a.arr_list.arr = [7, None] stack_2a.arr_list.num_items = 1 stack_2a.num_items = 1 self.assertEqual(stack_1a, stack_2a) stack_1l = StackLinked() stack_1l.push(7) stack_2l = StackLinked() stack_2l.top = stacks.Node(7, None) stack_2l.num_items = 1 self.assertEqual(stack_1l, stack_2l)
def test_stack_array(self): arr1 = StackArray() arr1.push(4) arr1.push(5) self.assertEqual(arr1.size(), 2) self.assertEqual(arr1.is_full(), True) arr1.enlarge() self.assertEqual(arr1.is_full(), False) arr1.push(6) arr1.push(7) self.assertEqual(arr1.is_full(), True) self.assertEqual(arr1.pop(), 7) arr1.pop() arr1.pop() arr1.pop() self.assertEqual(arr1.is_empty(), True) arr2 = StackArray() arr2.enlarge() arr2.enlarge() arr2.shrink() self.assertEqual(arr2.capacity, 4) arr2.enlarge() arr2.push(5) arr2.push(9) arr2.push(10) self.assertEqual(arr2.peek(), 10) arr3 = StackArray() self.assertEqual(arr3.peek(), None) print(arr2.arr) arr4 = StackArray() with self.assertRaises(IndexError): arr4.pop()
def delimiter_match(expression): """ Return True if an expressions contains correct pairings of delimiters. Return False otherwise""" open_delimiters = '({[' # opening delimiters close_delimiters = ')}]' # closing delimiters X = StackArray() # create StackArray instance for char in expression: #scan every character in the expression if char in open_delimiters: # if the character is an opening delimiter X.push(char) # push it on the stack elif char in close_delimiters: # if the character is a closing delimiter if X.is_empty(): return False # no match found if close_delimiters.index(char) != open_delimiters.index(X.pop()): return False # mismatch found return X.is_empty() # are all symbols matched?
def match_html(input_text): """ Return True if all HTML tags are properly matched, False otherwise""" X = StackArray() index = input_text.find('<') # find first '<' character (if any) while index != -1: next_tag = input_text.find('>', index+1) # find next '>' character if next_tag == -1: return False # invalid tag tag = input_text[index+1:next_tag] #strip away < > if not tag.startswith('/'): # this is opening tag X.push(tag) else: # this is closing tag if X.is_empty(): return False # nothing to match with if tag[1:]!=X.pop(): return False # mismatched delimiter index = input_text.find('<',next_tag+1) # find next '<' character if any return X.is_empty() # were all opening tags matched?
def postfix_eval(postfixExpr): """ Purpose """ s = StackArray(30) token = postfixExpr.split() for t in token: if t in "0123456789": #if the string character is in that string s.push(int(t)) # convent that string character into an integer else: op1 = s.pop() #pop the first two integer op2 = s.pop() result = doMath(t,op1,op2) # give a value for the operation if result == "ValueError": #check if it is dividing by 0 if so raise an Error raise ValueError("Value Error") else: s.push(result) #else add the result to the stack return s.pop() #return the value after it loops through all the operators
def test_size(self): stk_a = StackArray(4) stk_a.push(6) stk_a.push(7) stk_a.push(8) stk_a.push(9) self.assertTrue(stk_a.is_full()) with self.assertRaises(IndexError): stk_a.push(0) self.assertEqual(stk_a.size(), 4 ) self.assertEqual(stk_a.pop(), 9 ) self.assertEqual(stk_a.size(), 3 ) self.assertFalse(stk_a.is_empty())
def test_StackArray(self): stack = StackArray(3) self.assertRaises(IndexError, stack.pop) self.assertEqual(stack.is_empty(), True) stack.push('book1') stack.push('book2') self.assertEqual(stack.peek(), 'book2') self.assertEqual(stack.pop(), 'book2') self.assertEqual(stack.peek(), 'book1') stack.push('book2_2') stack.push('book3') self.assertRaises(IndexError, stack.push, 'book4') self.assertEqual(stack.size(), 3) self.assertEqual(stack.is_full(), True)
def postfix_eval(postfix_expr): """to evaluate a postfix expression into a value. Use the postfix_valid function described below to check the validity of the expression Args: list (postfix_expr): postfix expression for evaluation Returns: int: value of postfix_expr after evaluation Raises: ZeroDivisionError """ s = StackArray() expr = postfix_expr.split() for token in expr: if token[0] in '0123456789': res = token s.push(res) else: # token is operator op2 = s.pop() op2 = float(op2) if s.is_empty(): # token is ~ # could also be ~ for non-empty stack res = -1 * op2 else: op1 = s.pop() op1 = float(op1) if token == '^': res = op1**op2 elif token == '~': s.push(op1) res = -1 * op2 elif token == '*': res = op1 * op2 elif token == '/': if op2 == 0: raise ZeroDivisionError else: res = op1 / op2 elif token == '+': res = op1 + op2 else: # token == '-' res = op1 - op2 s.push(res) return res
def infix_to_postfix(infix_expr): """ Convert an infix expression into a postfix expression. Assumes valid inputs. Args: list (infix_expr): properly formatted/valid str for conversion Returns: str: a string of the converted postfix expression """ # Append adds new item to list # Concat creates a new list every time instead opstack = StackArray() res = [] lstr = infix_expr.split() # l_para = r_para = 0 # operator precedence dict prec = { # higher val = higher prec "(": 4, "^": 3, # r-to-l (i.e. 2^3^2 = 2^(3^2) ) "~": 3, # right-to-left (i.e. -3^2 = -9) # '*/+-' are associated left to right "*": 2, "/": 2, "+": 1, "-": 1 } for token in lstr: if token[0] in '0123456789': res.append(token) # not opstack.is_empty() guards against IndexError on empty peek if not opstack.is_empty() and opstack.peek() == '^': res.append(opstack.pop()) if not opstack.is_empty() and opstack.peek() == '~': res.append(opstack.pop()) elif token == '(': # l_para += 1 opstack.push(token) elif token == ')': # r_para += 1 # opstack can't be empty for proper formatted input while opstack.peek() != '(': res.append(opstack.pop()) opstack.pop() # remove left paran '(' else: # token is ^ ~ * / + -: <-- operators while not opstack.is_empty() and prec[token] <= prec[ opstack.peek()]: if opstack.peek() == '(': break elif token == '^' and opstack.peek() == '~': break else: res.append(opstack.pop()) opstack.push(token) # if l_para != r_para: # raise SyntaxError while not opstack.is_empty(): res.append(opstack.pop()) res = " ".join(res) res.strip() return res
def test_push(self): stk_a = StackArray(10) stk_a.push(3) self.assertEqual(stk_a.peek(), 3 ) self.assertEqual(stk_a.pop(), 3 ) self.assertTrue(stk_a.is_empty())