def infixConverter(equationString): numStack = Stack() numList = [] # operatorValues = {"/":2, "*":2, "+":1, "-":1} for variable in equationString: try: int(variable) numList.append(variable) except ValueError: if variable == "(": numStack.push(variable) elif variable == ")": while numStack.top() != "(": numList.append(numStack.pop()) numStack.pop() elif (variable == "*" or variable == "/"): if numStack.top() == "*" or numStack.top() == "/": numList.append(numStack.pop()) numStack.push(variable) else: numStack.push(variable) elif (variable == "+" or variable == "-"): numStack.push(variable) while numStack.length() != 0: numList.append(numStack.pop()) s = " " print(s.join(numList))
def correctBracket(givenString): charStack = Stack() for char in givenString: if char == '{' or char == '[' or char == '(': charStack.push(char) elif char == '}': if charStack.top() != '{': return 'INCORRECT' charStack.pop() elif char == ']': if charStack.top() != '[': return 'INCORRECT' charStack.pop() elif char == ')': if charStack.top() != '(': return 'INCORRECT' charStack.pop() return 'ITS CORRECT'
def bracketChecker(input_string): open_brackets = ['(', '[', '{'] close_brackets = [')', ']', '}'] stack = Stack() for char in input_string: if char in open_brackets: stack.push(char) elif char in close_brackets: if char == ')': if stack.top() != '(': return False stack.pop() elif char == ']': if stack.top() != '[': return False stack.pop() elif char == '}': if stack.top() != '{': return False stack.pop() return True
def palindrome_check_list(inlist): """ Determine whether inlist is a palindrome, using a stack. """ size = len(inlist) mid = size // 2 even = True if size % 2 == 1: even = False print('Midpoint is', mid, '; inlist is of EVEN length:', even) stack = Stack() pos = 0 while pos < mid: stack.push(inlist[pos]) pos = pos + 1 if not even: pos = pos + 1 while pos < len(inlist): print('mylist[', pos, ']=', inlist[pos], '; stack.top() =', stack.top()) #if inlist[pos] != stack.pop(): if not inlist[pos].is_equal(stack.pop()): return False pos = pos + 1 return True
def palindrome_check(string): """ Determine whether string is a palindrome, using a stack. """ mylist = list(string) size = len(mylist) mid = size // 2 even = True if size % 2 == 1: even = False print('Midpoint is', mid, '; string is of EVEN length:', even) stack = Stack() #create and return a stack object pos = 0 while pos < mid: #push first half of the string onto the stack stack.push(mylist[pos]) pos = pos + 1 if not even: pos = pos + 1 while pos < len(mylist): #now pop and compare the two half lists print('mylist[', pos, ']=', mylist[pos], '; stack.top() =', stack.top()) if mylist[pos] != stack.pop(): return False pos = pos + 1 print('This is a palindrome') return True