def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" RPN_list=[] s=Stack(30) str_list=input_str.split() for thing in str_list: if isNumber(thing): RPN_list.append(thing) elif thing == '(': s.push(thing) elif thing == ')': while s.peek()!= '(' and not s.is_empty(): RPN_list.append(s.pop()) s.pop() #exponential has highest precedence elif thing == '^': s.push(thing) elif thing == "*" or thing == "/": try: if s.peek() == "*" or s.peek() == "/" or s.peek() == "^" : while not s.is_empty() and s.peek() == "*" or s.peek() == "/" or s.peek() == "^": RPN_list.append(s.pop()) except: pass s.push(thing) elif thing == "+" or thing == "-": while not s.is_empty() and s.peek() != '(': RPN_list.append(s.pop()) s.push(thing) while s.size()!=0: RPN_list.append(s.pop()) return (' '.join(RPN_list))
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ** parentheses ( ) or numbers Returns a String containing a postfix expression """ output = [] stack = Stack(30) input = input_str.split() for item in input: if item.isnumeric(): output.append(item) elif item == '(': stack.push(item) elif item == ')': while ((not stack.is_empty()) and (stack.peek() != '(')): val1 = stack.pop() output.append(val1) try: stack.pop() except: raise PostfixFormatException("Insufficient operands") # an operator is encountered else: while ((not stack.is_empty()) and orderOfOperations(stack, item)): output.append(stack.pop()) stack.push(item) # pop all the operator from the stack while not stack.is_empty(): output.append(stack.pop()) return " ".join(output)
def test_is_empty(self): """Creating and testing empty stack""" stack = Stack(5) self.assertEquals(stack.is_empty(), True) """Testing non-empty stack""" stack2 = Stack(5, [5, 4, 3, 2]) self.assertEquals(stack2.is_empty(), False)
def stack_test(a): """ ------------------------------------------------------- Tests Use: stack_test(a) ------------------------------------------------------- Preconditions: a - list of data (list of ?) Postconditions: the methods of Stack are tested for both empty and non-empty stacks using the data in a: empty, push, pop, peek ------------------------------------------------------- """ s = Stack() print("a: {}".format(a)) #is_Empty print("Tests s.is_Empty: {}".format(s.is_empty())) array_to_stack(s, a) print("Tests s.is_Empty again: {}".format(s.is_empty())) print("Stack after array_to_stacks: ") for v in s: print(v) #push print("Pushes '21' to the top of the stack: ") s.push(21) #pop print("Tests pop: {}".format(s.pop())) #peek print("Tests peek: {}".format(s.peek())) print("Stack to array: ") stack_to_array(s, a) print(a) return
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ^ parentheses ( ) or numbers Returns a String containing a postfix expression """ stack = Stack(30) # Stack of size 30 operators = ["(", ")", ">>", "<<", "**", "*", "/", "+", "-"] # Allowed operands final_list = "" first_run = True split_string = input_str.split( ) # Split input string into usable chunks in a list for val in split_string: # Run through every value in list in order if val == "(": stack.push("(") elif val == ")": popping = True while popping: popped_value = stack.pop() if popped_value == "(": popping = False else: final_list += " " + popped_value elif val in operators: popping = True while popping: if stack.is_empty(): popping = False elif stack.peek() == "(": popping = False elif (val == ">>" or val == "<<") and operators.index(stack.peek()) > 3: popping = False elif val == "**" and operators.index(stack.peek()) > 3: popping = False elif (val == "*" or val == "/") and operators.index(stack.peek()) > 6: popping = False else: final_list += " " + stack.pop() stack.push(val) else: if first_run: final_list += str(val) first_run = False else: final_list += " " + str(val) popping = True while popping: if stack.is_empty(): popping = False else: final_list += " " + stack.pop() return final_list
def test_is_empty(self): stack1 = Stack(5) stack2 = Stack(3, [8, 12, 52]) self.assertTrue(stack1.is_empty()) self.assertFalse(stack2.is_empty()) stack1.push(5) self.assertFalse(stack1.is_empty())
def infix_to_postfix(input_str): '''Converts an infix expression to an equivalent postfix expression Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ** >> << parentheses ( ) or numbers Returns a String containing a postfix expression ''' operators = Stack(30) input_list = input_str.split(" ") postfix = "" for i in range(len(input_list)): type = type_check(input_list[i]) if type == 5: operators.push(input_list[i]) elif type == 6: while not operators.is_empty() and operators.peek() != "(": postfix += operators.pop() + " " operators.pop() elif type == 0: postfix += input_list[i] + " " else: if operators.is_empty(): operators.push(input_list[i]) else: while not operators.is_empty() and ( type <= type_check(operators.peek()) < 5 and not type == type_check(operators.peek()) == 3): postfix += operators.pop() + " " operators.push(input_list[i]) while not operators.is_empty(): postfix += operators.pop() + " " return postfix[:len(postfix) - 1]
def test3(self): stack3 = Stack(3) stack3.push(7) stack3.push(6) stack3.push(5) stacktest = Stack(0) self.assertEqual(stack3.peek(), 5) self.assertEqual(stack3.size(), 3) self.assertFalse(stack3.is_empty()) self.assertTrue(stacktest.is_empty())
def infix_to_postfix(input_str): # Converts an infix expression to an equivalent postfix expression # Input argument: a string containing an infix expression where tokens are # space separated. Tokens are either operators + - * / ^ parentheses ( ) or numbers # Returns a String containing a postfix expression #Precedent orderOfOperations = { '<<': 5, '>>': 5, '^': 4, '**': 4, '*': 2, '/': 2, '+': 1, '-': 1, '(': 0 } #Delimiter infixList = input_str.split(" ") #Sets up stack with capacity of the len of the delimited string opStack = Stack(len(infixList)) #Output holder postfixOutput = [] #For each element in the list of infix for token in infixList: try: #Using ast.literal_eval postfixOutput.append(ast.literal_eval(token)) except: #Open ( push if token == "(": opStack.push(token) #Close ) stack pop elif token == ")": head = opStack.pop() while head != "(": postfixOutput.append(head) head = opStack.pop() elif orderOfOperations[token] == 4: opStack.push(token) else: #When the stack isn't empty and the ooO on the stack is greater then the current ooO while not (opStack.is_empty()) and ( orderOfOperations[opStack.peek()] >= orderOfOperations[token]): postfixOutput.append(opStack.pop()) opStack.push(token) while not (opStack.is_empty()): postfixOutput.append(opStack.pop()) #Recreate the string join together return " ".join(str(pfUnit) for pfUnit in postfixOutput)
def test_simple(self): stack = Stack(5) self.assertTrue(stack.is_empty()) stack.push(0) self.assertFalse(stack.is_empty()) self.assertFalse(stack.is_full()) stack.push(1) stack.push(2) stack.push(3) stack.push(4) self.assertTrue(stack.is_full()) self.assertEqual(stack.size(), 5)
def mirror_stack(s, valid_chars, m): """ ------------------------------------------------------- Determines if string is a mirror of characters in valid_chars around the pivot m. A mirror is of the form LmR, where L is the reverse of R, and L and R contain only characters in valid_chars. Use: is_mirror = mirror_stack(string, valid_chars, m) ------------------------------------------------------- Preconditions: string - a string (str) valid_chars - a string of valid characters (str) m - the mirror pivot string (str - one character not in valid_chars) Postconditions: returns is_mirror (int) - one of: IS_MIRROR - string is of the form LmR BAD_CHAR - L or R contains characters not in valid_chars NO_MIRROR - string does not contain m MORE_LEFT - too many characters in L MORE_RIGHT - too many characters in R MISMATCHED - some characters in L and R don't match ------------------------------------------------------- """ stack = Stack() is_mirror = (len(s) == 0 or len(s) % 2 == 0) i = 0 while is_mirror and i < len(s) and s[i] != m: if s[i] in valid_chars: stack.push(s[i]) i+=1 else: is_mirror = BAD_CHAR i +=1 i +=1 while is_mirror and i < len(s) and not stack.isempty(): val = stack.pop() if val!= s[i]: is_mirror = MISMATCHED else: i+=1 if not stack.is_empty(): is_mirror = MORE_LEFT elif i < len(s) and stack.is_empty(): is_mirror = MORE_RIGHT return is_mirror
def prefix_to_postfix(input_str): """Converts a prefix expression to an equivalent postfix expression""" """Input argument: a string containing a prefix expression where tokens are space separated. Tokens are either operators + - * / ** parentheses ( ) or numbers Returns a String containing a postfix expression(tokens are space separated)""" stack = Stack(30) operators = ['+', '-', '*', '/', '**'] input = input_str.split() result = "" # Reversing the order input_reverse = input[::-1] # iterating through individual tokens for item in input_reverse: # if token is operator if item in operators: a = stack.pop() b = stack.pop() temp = a + b + item stack.push(temp) else: stack.push(item) # printing final output while not stack.is_empty(): result = result + stack.pop() return " ".join(result)
def test1(self): stack1 = Stack(1) stack1.push(2) self.assertFalse(stack1.is_empty()) self.assertTrue(stack1.is_full()) with self.assertRaises(IndexError): #checks for exception stack1.push(1)
def test_simple(self): stack = Stack(5) self.assertRaises(IndexError, stack.pop) stack.push(0) self.assertFalse(stack.is_empty()) self.assertFalse(stack.is_full()) self.assertEqual(stack.size(),1)
def test_simple(self): stack = Stack(5) stack.push(0) self.assertFalse(stack.is_empty()) self.assertFalse(stack.is_full()) self.assertEqual(stack.size(), 1) stack.push(4) stack.push(9) self.assertEqual(stack.size(), 3) stack.push(8) stack.push(7) with self.assertRaises(IndexError): stack.push(6) stack.pop() self.assertEqual(stack.size(), 4) self.assertEqual(stack.peek(), 8) stack.pop() stack.pop() stack.pop() self.assertEqual(stack.pop(), 0) self.assertEqual(stack.size(), 0) with self.assertRaises(IndexError): stack.pop() with self.assertRaises(IndexError): stack.peek()
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ^ parentheses ( ) or numbers Returns a String containing a postfix expression """ stack = Stack(30) tokens = input_str.split(" ") RPN = "" for token in tokens: if is_int(token) or is_float(token): if RPN == "": RPN = token else: RPN = RPN + " " + token elif token == "(": stack.push(token) elif token == ")": while stack.peek() != "(": RPN = RPN + " " + stack.pop() stack.pop() elif is_operator(token): while (stack.is_empty() == False) and is_operator( stack.peek()) and has_precedence(token, stack.peek()): RPN = RPN + " " + stack.pop() stack.push(token) while stack.size() > 0: RPN = RPN + " " + str(stack.pop()) return RPN
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ^ parentheses ( ) or numbers Returns a String containing a postfix expression """ s = Stack(30) post = '' tokens = input_str.split() op_prec = {'+': 1, '-': 1, '*': 2, '/': 2, '**': 3, '<<': 4, '>>': 4} operators = ['+', '-', '*', '/', '**', '<<', '>>'] if input_str == '': return '' for char in tokens: if post == '' and char.lstrip('-').replace('.', '', 1).isdigit(): post += char elif char.lstrip('-').replace('.', '', 1).isdigit(): post += ' ' + char elif char == '(': s.push(char) elif char in operators: if not s.is_empty(): o2 = s.peek() while s.size() > 0: o2 = s.peek() if o2 == '(': break if char == '**': if op_prec[char] < op_prec[o2]: post += ' ' + s.pop() else: break elif op_prec[char] <= op_prec[o2]: post += ' ' + s.pop() else: break s.push(char) elif char == ')': o2 = s.peek() while o2 != '(': post += ' ' + s.pop() if not s.is_empty(): o2 = s.peek() s.pop() while not s.is_empty(): post += ' ' + s.pop() return post
def infix_to_postfix(input_str): """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ** parentheses ( ) or numbers Returns a String containing a postfix expression """ s = Stack(30) output = [] ops1 = ['+', '*', '**', '<<'] ops2 = ['-', '/', '**', '>>'] for i in input_str.split(): try: if '.' in i: output.append(str(float(i))) else: output.append(str(int(i))) except ValueError: if s.is_empty(): s.push(i) elif i == '(': s.push('(') elif i == ')': c = s.peek() while c != '(': output.append(s.pop()) c = s.peek() s.pop() else: op = s.peek() if op != '(': x = ops1.index(i) if i in ops1 else ops2.index(i) y = ops1.index(op) if op in ops1 else ops2.index(op) if x > y: s.push(i) if x == y: if i == '**' and op == '**': s.push(i) else: output.append(s.pop()) s.push(i) if x < y: while x <= y: try: if i == '**' and op == '**': break else: output.append(s.pop()) op = s.peek() y = ops1.index( op) if op in ops1 else ops2.index(op) except IndexError: break except ValueError: break s.push(i) else: s.push(i) for i in range(s.size()): output.append(s.pop()) return ' '.join(output)
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ^ parentheses ( ) or numbers Returns a String containing a postfix expression """ prec = {} prec['<<'] = 5 prec['>>'] = 5 prec['**'] = 4 prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 stack = Stack(30) PFN = [] inputter = input_str.split() for val in inputter: if val.isdigit() == True: PFN.append(val) elif '.' in val: PFN.append(val) elif '-' in val and len(val) > 1: PFN.append(val) elif val == '(': stack.push(val) elif val == ')': while stack.peek() != '(': PFN.append(stack.pop()) stack.pop() else: if val != '**': while (stack.is_empty() == False) and (prec[stack.peek()] >= prec[val]): PFN.append(stack.pop()) elif val == '**': while (stack.is_empty() == False) and (prec[stack.peek()] > prec[val]): PFN.append(stack.pop()) stack.push(val) while stack.is_empty() == False: PFN.append(stack.pop()) x = ' ' PFN = x.join(PFN) return PFN
def test_simple(self): stack = Stack(5) stack.push(0) self.assertFalse(stack.is_empty()) self.assertFalse(stack.is_full()) self.assertEqual(stack.size(), 1) stack.push(1) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.peek(), 0)
def test_pop(self): stack = Stack(3, [8, 12, 52]) self.assertEqual(stack.pop(), 52) self.assertEqual(stack.pop(), 12) self.assertEqual(stack.num_items, 1) self.assertEqual(stack.pop(), 8) self.assertTrue(stack.is_empty()) with self.assertRaises(IndexError): # used to check for exception stack.pop()
def postfix_eval(input_str): """Evaluates a postfix expression""" """Input argument: a string containing a postfix expression where tokens are space separated. Tokens are either operators + - * / ^ or numbers Returns the result of the expression evaluation. Raises an PostfixFormatException if the input is not well-formed""" s = Stack(30) tokens = input_str.split() operators = ['+', '-', '*', '/', '**', '<<', '>>'] if input_str == '': return '' for char in tokens: if char in operators: try: n2 = s.pop() n1 = s.pop() except IndexError: raise PostfixFormatException('Insufficient operands') if char == '+': result = n1 + n2 s.push(result) if char == '-': result = n1 - n2 s.push(result) if char == '*': result = n1 * n2 s.push(result) if char == '/': if n2 == 0: raise ValueError('Cannot divide by 0!') result = n1 / n2 s.push(result) if char == '**': result = n1**n2 s.push(result) if char == '<<': if type(n1) == float or type(n2) == float: raise PostfixFormatException('Illegal bit shift operand') result = n1 << n2 s.push(result) if char == '>>': if type(n1) == float or type(n2) == float: raise PostfixFormatException('Illegal bit shift operand') result = n1 >> n2 s.push(result) elif char.lstrip('-').replace('.', '', 1).isdigit(): if '.' not in char: s.push(int(char)) else: s.push(float(char)) else: raise PostfixFormatException('Invalid token') final = s.pop() if not s.is_empty(): raise PostfixFormatException('Too many operands') return final
def test2(self): stack = Stack(4) self.assertTrue(stack.is_empty()) stack.push(None) stack.push(4) stack.push(1) stack.push(7) self.assertTrue(stack.is_full()) self.assertEqual(stack.pop(), 7) self.assertEqual(stack.size(), 3)
def stack_test(a): """ ------------------------------------------------------- Tests Use: stack_test(a) ------------------------------------------------------- Preconditions: a - list of data (list of ?) Postconditions: the methods of Stack are tested for both empty and non-empty stacks using the data in a: is_empty, push, pop, peek ------------------------------------------------------- """ s = Stack() # tests for the stack methods go here # print the results of the method calls and verify by hand print("is_empty for an empty stack:") is_empty = s.is_empty() print("{}".format(is_empty)) try: print("pop empty:") pop = s.pop() print("{}".format(pop)) except: print("pop empty failed") try: print("peek empty:") peek = s.peek() print("{}".format(peek)) except: print("peek empty failed") try: print("push:") for j in a: s.push(j) for i in s: print("{}".format(i)) except: print("push failed") try: print("pop:") pop = s.pop() print("{}".format(pop)) except: print("pop failed") try: print("peek:") peek = s.peek() print("{}".format(peek)) except: print("peek failed") return
def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" """Input argument: a string containing an infix expression where tokens are space separated. Tokens are either operators + - * / ** << >> or numbers (integers or floats) Returns a String containing a postfix expression """ stack = Stack(30) arr = str.split(input_str) rpn = "" i = 0 while i<len(arr): #checks if number try: float(arr[i]) if rpn=="": rpn = arr[i] else: rpn = rpn + " " + arr[i] except: if arr[i]=="(": stack.push(arr[i]) elif arr[i]==")": while stack.peek()!="(": rpn = rpn + " " + stack.pop() stack.pop() #checks if operator elif arr[i]=="+" or arr[i]=="-" or arr[i]=="**" or arr[i]=="*" or arr[i]=="/" or arr[i]=="<<" or arr[i]==">>": if arr[i]=="**": while not stack.is_empty() and (stack.peek()=="+" or stack.peek()=="-" or stack.peek()=="**" or stack.peek()=="*" or stack.peek()=="/" or stack.peek()=="<<" or stack.peek()==">>") and prec(arr[i])<prec(stack.peek()): rpn = rpn + " " + stack.pop() else: while not stack.is_empty() and (stack.peek()=="+" or stack.peek()=="-" or stack.peek()=="**" or stack.peek()=="*" or stack.peek()=="/" or stack.peek()=="<<" or stack.peek()==">>") and prec(arr[i])<=prec(stack.peek()): rpn = rpn + " " + stack.pop() stack.push(arr[i]) i += 1 while not stack.is_empty(): rpn = rpn + " " + stack.pop() return rpn
def stack_test(a): """ ------------------------------------------------------- Tests Use: stack_test(a) ------------------------------------------------------- Preconditions: a - list of data (list of ?) Postconditions: the methods of Stack are tested for both empty and non-empty stacks using the data in a: is_empty, push, pop, peek ------------------------------------------------------- """ s = Stack() print("Empty:", s.is_empty()) array_to_stack(s, a) print(s.peek()) print(s.pop()) print("Empty:", s.is_empty()) stack_to_array(s, a) return
class TestStack(unittest.TestCase): def setUp(self): self.s = Stack() def test_is_empty(self): self.assertTrue(self.s.is_empty()) def test_is_not_empty(self): # 这里不使用 push,避免造成测试相互依赖 self.s._list.append(1) self.assertFalse(self.s.is_empty()) def test_push_pop(self): elements = [1, 2, 3] for e in elements: self.s.push(e) for e in reversed(elements): self.assertEqual(e, self.s.pop()) def test_pop_empty(self): with self.assertRaises(ValueError): self.s.pop()
def test_simple(self): stack = Stack(5) self.assertTrue(stack.is_empty()) stack.push(0) self.assertFalse(stack.is_empty()) self.assertFalse(stack.is_full()) self.assertEqual(stack.size(), 1) stack.push(1) self.assertEqual(stack.size(), 2) self.assertEqual(stack.capacity, 5) self.assertEqual(stack.peek(), 1) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.size(), 1) for i in range(4): stack.push(1) with self.assertRaises(IndexError): stack.push(1) with self.assertRaises(IndexError): s = Stack(1) s.pop() with self.assertRaises(IndexError): e = Stack(1) e.peek() self.assertTrue(stack.is_full())
def reverse(self): """ ------------------------------------------------------- Reverses the order of the elements in a queue. Use: q.reverse() ------------------------------------------------------- Postconditions: The contents of q are reversed in order with respect to their order before the operation was called. ------------------------------------------------------- """ from stack_array import Stack s = Stack() while len(self._values) > 0: s.push(self._values[0]) self.remove() while s.is_empty() == False: self.insert(s.pop())
def reverse(self): """ ------------------------------------------------------- Reverses the order of the elements in a queue. Use: q.reverse() ------------------------------------------------------- Postconditions: The contents of q are reversed in order with respect to their order before the operation was called. ------------------------------------------------------- """ s = Stack() print('use') while len(self._values) > 0: v = self._values.pop(0) s.push(v) while not s.is_empty(): self._values.append(s.pop()) return