def main(): # Use a stack in order to check the bracket balance brackets = array_stack.ArrayStack() input_string = input( "Enter a string consisiting of only brackets, whose balance is to be checked\n" ) opening_bracket_list = ["{", "(", "["] closing_bracket_list = ["}", ")", "]"] for bracket in input_string: # Check balance of the input string if bracket in opening_bracket_list: brackets.push(bracket) elif bracket in closing_bracket_list: if brackets.is_empty(): print("Imbalanced") return elif not check_matching_brackets(brackets.pop(), bracket): print("Imbalanced") return if brackets.is_empty(): print("Balanced") else: print("Imbalanced")
def main(): # We perform bangle wearing and removing operations on this hand hand = array_stack.ArrayStack() iterations = int( input("Enter the number of operations you want to perform\n")) for num in range(0, iterations): print("Enter the operation you want to perform:\n") operation = int( input( "1) Wear a bangle\n2) Remove a bangle\n3) Count the number of bangles currently on your hand\n" )) if operation == 1: # Wear a bangle color_input = input("Enter colour\n") hand.push(color_input) hand.display() elif operation == 2: # Remove a bangle print(hand.pop()) hand.display() elif operation == 3: # Count number of bangles print(hand.size()) hand.display() else: print("Whoops! Not sure what you meant there. Bye bye!") exit(0)
def calculate(expression): #calculate the result of the postfix expression nums = array_stack.ArrayStack() for e in expression: if type(e) is int: #check if element is a number or not nums.push(float(e)) else: nums.push(solve(nums, e)) return (nums.pop())
def calculatePostfix(formula): stk = array_stack.ArrayStack() p_notation = formula.split(" ") # split elements by the space # walk through the formula and calculate # if the user did not input a postfix notation, raise for walker in p_notation: # if the walker meets operator, pop two element and push the calculation result if walker == '+': tmp = stk.pop() try: stk.push(stk.pop() + tmp) except: print("your formula seems not a postfix notation") return None elif walker == '-': tmp = stk.pop() try: stk.push(stk.pop() - tmp) except: print("your formula seems not a postfix notation") return None elif walker == '*': tmp = stk.pop() try: stk.push(stk.pop() * tmp) except: print("your formula seems not a postfix notation") return None elif walker == '/': tmp = stk.pop() if tmp == float(0): # if the function tries divide by 0 print("division by 0 is impossible") return None try: stk.push(stk.pop() / tmp) except: print("your formula seems not a postfix notation") return None elif walker.isnumeric(): # if number, push it stk.push(float(walker)) # if the string contains except the operands and operators, else: print("wrong data!") return None return stk
def reverse_file(filename): """Overwrite given file with its contents line-by-line reversed.""" S = array_stack.ArrayStack() original = open(filename, 'r') for line in original: S.push(line.rstrip('\n')) # we will re-insert newlines when writing original.close() # now we overwrite with contents in LIFO order output = open(filename, 'w') # reopening file overwrites original while not S.is_empty(): output.write(S.pop() + '\n') # re-insert newline characters output.close()
def is_matching(expr): s = array_stack.ArrayStack() lefty = '({[' righty = ')}]' for i in expr: if lefty.__contains__(i): s.push(i) elif righty.__contains__(i): if s.is_empty(): return False elif lefty.index(s.pop()) != righty.index(i): return False return s.is_empty()
def is_matched_html(raw): """Definded in COMP 2002 materials """ S = array_stack.ArrayStack() j = raw.find('<') # find first '<' character (if any) while j != -1: k = raw.find('>', j + 1) # find next '>' character from the first '<' if k == -1: return False # invalid tag (since we cannot find any corresponding tag) tag = raw[j + 1:k] # strip away the tags < > # -------------------- this is the original version from the material -------------------- # # if not tag.startswith('/'): # means it is opening tag # S.push(tag) # what data gonna putted in? (reference of list or the string?) # else: # means it is closing tag # if S.is_empty(): # return False # nothing to match with # #if tag[1:] != S.pop(): # return False # mismatched delimiter # ---------------------------------------------------------------------------------------- # # -------------------- this is the modified version -------------------- # if tag.startswith('/'): # if it is closing tag if S.is_empty(): return False # nothing to match with if tag[1:] != S.pop(): return False # mismatched delimiter else: # if it is not a closing tag (opening tag) tmp = tag.split( " " ) # split elements by the space (as the tag attributes usually distinguished by the space) tmp = tmp[ 0] # and save the 0'th element which is the tag name only S.push(tmp) # push the tag name only (except attributes) # --------------------------------------------------------------------- # j = raw.find('<', k + 1) # find next '<' character (if any) return S.is_empty() # were all opening tags matched?
print("Stack adds "+str(value1)+" and "+str(value2)) newValue = float(value1)+float(value2) elif(operand=='-'): newValue = float(value2)-float(value1) print("Stack subtracts "+str(value2)+" and "+str(value1)) elif(operand=='/'): newValue = float(value2)/float(value1) print("Stack divides "+str(value2)+" and "+str(value1)) elif(operand=='*'): newValue = float(value2)*float(value1) print("Stack multiplies "+str(value1)+" and "+str(value2)) return newValue stack = AS.ArrayStack() outputStack = AS.ArrayStack() postfixString = "52+83-*4/" for x in postfixString: stack.push(x) print("Stack reads "+x) if (x=='+' or x=='-' or x=='/' or x=='*'): stack.pop() if(stack.is_empty()): val1 = outputStack.pop() val2 = outputStack.pop()
import array_stack stack = array_stack.ArrayStack() # input_file = open("input.txt", "r") input_file = "4 6 + 13 11 - / 3 *" answer_list = [] numerical_vals = "1234567890" valid_operators = "+ - * /" def calculate(expression): hold = [] reversed_hold = [] exp = "" expression_list = expression.split() for value in expression_list: if value.isnumeric(): stack.push(value) elif value in valid_operators: hold.append(stack.pop()) hold.append(value) hold.append(stack.pop()) for i in range(3): reversed_hold.append(hold.pop()) exp = ''.join(reversed_hold) reversed_hold = [] hold = []
def main(): # Use a stack in order to check the bracket balance brackets = array_stack.ArrayStack() input_string = input("Enter a string consisiting of only brackets, whose balance is to be checked\n") for bracket in input_string: