def infix_to_postfix(input_str): """Converts an infix expression to an equivalent postfix expression""" inputList = input_str.split() rpnString = '' infixStack = Stack(30) for item in inputList: try: if item.isdigit() == True: num = int(item) else: num = float(item) rpnString += item + ' ' except: if item == '(': infixStack.push(item) elif item == ')': while infixStack.peek() != '(': rpnString += infixStack.pop() + ' ' infixStack.pop() else: if infixStack.size() > 0: o1 = item o2 = infixStack.peek() if checkPrec(o1, o2) == False and o2 != '(': rpnString += item + ' ' + infixStack.pop() + ' ' else: rpnString += infixStack.pop() + ' ' infixStack.push(item) else: infixStack.push(item) for i in range(infixStack.size()): rpnString += infixStack.pop() + ' ' rpnString = rpnString[:-1] return rpnString
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 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 ''' 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 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_empty_stack(self): stack = Stack(0) with self.assertRaises(IndexError): stack.pop() with self.assertRaises(IndexError): stack.peek() with self.assertRaises(IndexError): stack.push(1)
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 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 DO NOT USE PYTHON'S EVAL FUNCTION!!!''' if postfix_valid(input_str): numbers = Stack(30) input_list = input_str.split(" ") i = 0 while i < len(input_list): type = type_check(input_list[i]) if type == 0: numbers.push(input_list[i]) else: if input_list[i] == "+": a = float(numbers.pop()) b = float(numbers.pop()) numbers.push(a + b) elif input_list[i] == "-": a = float(numbers.pop()) b = float(numbers.pop()) numbers.push(b - a) elif input_list[i] == "*": a = float(numbers.pop()) b = float(numbers.pop()) numbers.push(a * b) elif input_list[i] == "/": a = float(numbers.pop()) b = float(numbers.pop()) if a == 0: raise ValueError numbers.push(b / a) elif input_list[i] == "**": a = float(numbers.pop()) b = float(numbers.pop()) numbers.push(b**a) elif input_list[i] == "<<": a = float(numbers.pop()) b = float(numbers.pop()) if a == int(a) and b == int(b): numbers.push(int(b) << int(a)) else: raise PostfixFormatException( "Illegal bit shift operand") elif input_list[i] == ">>": a = float(numbers.pop()) b = float(numbers.pop()) if a == int(a) and b == int(b): numbers.push(int(b) >> int(a)) else: raise PostfixFormatException( "Illegal bit shift operand") i += 1 if int(numbers.peek()) == float(numbers.peek()): return int(numbers.pop()) return numbers.pop()
def test2(self): stack2 = Stack(5) stack2.push(3) stacktest = Stack(0) self.assertEqual(stack2.pop(), 3) with self.assertRaises(IndexError): #checks for exception stacktest.pop() with self.assertRaises(IndexError): #checks for exception stacktest.peek()
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""" 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 test3(self): stack = Stack(2) with self.assertRaises( IndexError): # uses context manager to check exception stack.pop() with self.assertRaises( IndexError): # uses context manager to check exception stack.peek() stack.push(3) self.assertNotEqual(stack.peek(), 2) stack.push(2) self.assertEqual(stack.peek(), 2) with self.assertRaises( IndexError): # uses context manager to check exception stack.push(7)
def test_peek(self): """Cant peek if you're empty *points finger at own head*, peek returns index error""" stack = Stack(5, []) with self.assertRaises(IndexError): stack.peek() """Testing non-empty stacks. Peek returns the item & does not remove item from stack""" stack.push(-1000) self.assertEqual(stack.__repr__(), "Stack(5, [-1000])") self.assertEqual(stack.peek(), -1000) self.assertEqual(stack.__repr__(), "Stack(5, [-1000])") stack2 = Stack(5, [1, 2, 3, 4, 5]) self.assertEqual(stack2.__repr__(), "Stack(5, [1, 2, 3, 4, 5])") self.assertEqual(stack2.peek(), 5) self.assertEqual(stack2.__repr__(), "Stack(5, [1, 2, 3, 4, 5])")
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 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""" operators = ["<<", ">>", "**", "*", "/", "+", "-"] equation = input_str.split() stack = Stack(len(equation)) for i in range(len(equation)): if is_num(equation[i]): stack.push(equation[i]) elif equation[i] in operators: if stack.size() < 2: raise PostfixFormatException("Insufficient operands") first_num = stack.pop() second_num = stack.pop() if first_num == "0" and equation[i] == "/": raise ValueError try: total = eval(str(second_num) + str(equation[i]) + str(first_num)) except TypeError: raise PostfixFormatException("Illegal bit shift operand") stack.push(str(total)) else: raise PostfixFormatException("Invalid token") if stack.size() > 1: raise PostfixFormatException("Too many operands") if stack.size() == 0: return "" return float((stack.peek()))
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 testInfix(inputString): inputList = inputString.split() rpnString = '' infixStack = Stack(30) for item in inputList: if item.isdigit(): rpnString += item else: try: rpnString += str(float(item)) except: pass if infixStack.size() > 0: o1 = item o2 = infixStack.peek() if o1 != '**': if getPrecVal(o1) <= getPrecVal(o2) and infixStack.size() > 0: rpnString += infixStack.pop() elif o1 == '**': if getPrecVal(o1) < getPrecVal(o2) and infixStack.size() > 0: rpnString += infixStack.pop() infixStack.push(item) for i in range(infixStack.size()): rpnString += infixStack.pop() return rpnString
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) #Delimiter + Reverse prefixString = list(reversed(input_str.split(" "))) #Stack setup with capacity equal to len of list prefixStack = Stack(len(prefixString)) #For each element in the list for token in prefixString: #Token checker if token in "*/+-^**>><<": #Pops top 2 then assembles as postfix numberOne = prefixStack.pop() numberTwo = prefixStack.pop() tempString = numberOne + " " + numberTwo + " " + token #Pushes string back on the the stack prefixStack.push(tempString) else: prefixStack.push(token) #Returns the string accumulator return prefixStack.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 """ 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): """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 test4(self): stack = Stack(3) stack.push(None) self.assertEqual(stack.peek(), None) stack.push(3) stack.push(-2) stack.pop() stack.pop() stack.pop() self.assertEqual(stack.size(), 0)
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): """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 """ input_str = input_str.split(" ") output_str = '' inStack = Stack(len(input_str) + 1) for char in input_str: if num(char): output_str = output_str + char + ' ' if char is '(': inStack.push(char) if char is ')': while True: r = inStack.pop() if opp(r): output_str = output_str + r + ' ' if r is '(': break #raise PostfixFormatException if opp(char): while True: try: if not opp(inStack.peek()): raise IndexError op = inStack.peek() if char != '**' and precidence(char, op): output_str = output_str + op + ' ' inStack.pop() elif char == '**' and precidence(char, op, True): output_str = output_str + op + ' ' inStack.pop() else: break except: break inStack.push(char) for i in range(inStack.size()): finals = inStack.pop() output_str = output_str + finals + ' ' return output_str.strip()
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 """ my_stack = Stack(30) # initialize stack input_list = input_str.split() rpn_expression = "" if len(input_list) == 1: # if length is 1 just return token rpn_expression = input_str return rpn_expression for token in input_list: if my_is_digit( token ) is True: # if token is a operand append to rpn expression rpn_expression += token + " " else: if token == "(": # if token is ( push to stack my_stack.push("(") elif token == ")": # if token is ) remove items from stack until ( next_operator = my_stack.peek() while next_operator != "(": rpn_expression += my_stack.pop() + " " next_operator = my_stack.peek() my_stack.pop() else: if my_is_operator(token) is True: # order of operations while statement while (my_stack.is_empty() is False) and (my_is_operator( my_stack.peek()) is True) and (order_of_operations( my_stack, token) is True): rpn_expression += my_stack.pop() + " " my_stack.push(token) for operators in range( 0, my_stack.num_items ): # move rest of operators from stack to rpn expression if my_is_operator(my_stack.peek()) is True: rpn_expression += my_stack.pop() return rpn_expression
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 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 """ order = {'-': 1, '+': 1, '*': 2, '/': 2, '**': 3, '>>': 4, '<<': 4} op_stack = Stack(30) output_expression = [] ops = ['+', '-', '*', '/', '**', '>>', '<<'] input_str = input_str.split(" ") for num in input_str: if num == "(": op_stack.push(num) elif num == ")": while op_stack.peek() != '(': output_expression.append(op_stack.pop()) op_stack.pop() elif num not in ops: # if num is a number, add it to the stack output_expression.append(num) else: if op_stack.size() > 0: n = op_stack.peek() if n == "(": op_stack.push(num) elif order[num] <= order[n]: k = op_stack.pop() output_expression.append(k) # remove operators on the stack; append them to the output op_stack.push(num) else: op_stack.push(num) else: op_stack.push(num) while op_stack.is_empty() is False: # when the input expression has been processed, check the op_stack. n = op_stack.pop() output_expression.append(n) # any operators still on the stack are removed and appended to output stack. new = ' '.join(output_expression) return new
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: empty, push, pop, peek ------------------------------------------------------- """ s = Stack() array_to_stack(s, a) if s.is_empty() == True: print("Stack is empty") else: print("Stack is not empty") for i in s: print(i) print("Test Peek: {}".format(s.peek())) print("Test pop: {}".format(s.pop())) print("Test peek again: {}".format(s.peek())) # tests for the stack methods go here # print the results of the method calls and verify by hand return
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())
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def test_init(self): self.assertEqual(self.stack.get_size(), 0) new_stack = Stack("Bob") self.assertEqual(new_stack.get_size(), 1) def test_push(self): initial_size = self.stack.get_size() self.stack.push("Bob") self.assertEqual(self.stack.get_size(), initial_size + 1) def test_peek(self): self.stack.push("Adrian") self.stack.push("Bob") self.stack.push("Claire") self.assertEqual(self.stack.peek(), "Claire") def test_pop(self): self.stack.push("Adrian") self.stack.push("Bob") self.stack.push("Claire") initial_size = self.stack.get_size() popped_item = self.stack.pop() self.assertEqual(popped_item, "Claire") self.assertEqual(self.stack.get_size(), initial_size - 1) def test_clear(self): self.stack.push("Adrian") self.stack.push("Bob") self.stack.push("Claire") self.assertEqual(self.stack.get_size(), 3) self.stack.clear() self.assertEqual(self.stack.get_size(), 0) def test_get_size(self): self.stack.push("Bob") self.assertEqual(self.stack.get_size(), 1)