def infixToPostfix(infixexpr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec[")"] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() tokenList.reverse() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == ')': opStack.push(token) elif token == '(': topToken = opStack.pop() while topToken != ')': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) postfixList.reverse() return " ".join(postfixList)
def infixTOPost(expr): S = Stack() sp = expr.split() i = 0 res = '' while i != len(sp): symb = sp[i] i = i + 1 if operand(symb): res = res + ' ' + symb elif operator(symb): while not S.isEmpty() and not OpeningPara( S.top()) and HasHigherPre(S.top(), symb): res = res + ' ' + S.top() S.pop() S.push(symb) elif OpeningPara(symb): S.push(symb) elif ClosingPara(symb): while not S.isEmpty() and not OpeningPara(S.top()): res = res + ' ' + S.top() S.pop() S.pop() while not S.isEmpty(): res = res + ' ' + S.top() S.pop() return res
def eval_postfix(s): """Evaluates the postfix expression 's'.""" S = Stack() for ch in s: if ch in ('+', '-', '*', '/'): if S.isEmpty() is True: return "invalud expr" else: b = S.pop() if S.isEmpty() is True: return "invalid expr" else: a = S.pop() res = expr(a, b, ch) S.push(res) elif ch == ' ': pass else: S.push(ch) ans = S.pop() if S.isEmpty() is False: return "This is a false expr" return ans
def isMatched(expr): """Checks if the expression 'expr' has matching opening/closing symbols.""" #a=list(expr) #print(a) #b=0 S = Stack() l = len(expr) i = 0 while i != l: symb = expr[i] i = i + 1 if symb == '{' or symb == '[' or symb == '(': t = symb S.push(symb) elif symb == '}' or symb == ']' or symb == ')': if S.isEmpty(): return False else: left = S.pop() if not match(left, symb): return False if S.isEmpty(): return True else: return False
def eval_prefix(expr): s = Stack() for i in range(len(expr) - 1, -1, -1): ch = expr[i] if ch in ('+', '-', '*', '/'): if s.isEmpty() is True: return "invalid expr" else: b = s.pop() if s.isEmpty() is True: return "invalid expr" else: a = s.pop() res = find(b, a, ch) s.push(res) elif ch == ' ': pass else: s.push(ch) ans = s.pop() if s.isEmpty() is False: return "This is a false expr" return ans
def post_to_pre(strs): s = strs.split() St = Stack() final = "" for value in s: if value in ['+', '-', '*', '/', '%']: a = St.Pop() b = St.Pop() final = str(value) + " " + str(b) + " " + str(a) St.Push(final) elif value.isalpha(): St.Push(value) elif is_number(value): St.Push(value) else: print("Error") exit(0) return St.Top()
def isMatched(expr): """Checks if the expression 'expr' has matching opening/closing symbols.""" S = Stack() n = len(expr) for i in range(0, n): symb = expr[i] #next symbol # print(symb) if symb in ['{', '(', '[']: S.Push(symb) elif symb in ['}', ')', ']']: if S.isEmpty(): return False if S.Top() == '{' and symb == '}': S.Pop() elif S.Top() == '(' and symb == ')': S.Pop() elif S.Top() == '[' and symb == ']': S.Pop() else: continue if S.isEmpty(): return True else: return False
def push(self, val) -> None: """Adds `val` to top of set of stacks, creating new stack if necessary""" if self.isempty() or len(self.stackset.peek()) == self.MAXSIZE: s = Stack([val]) self.stackset.push(s) else: self.stackset.peek().push(val) self.length += 1
def __init__(self, arr=None, max_stack_size: int = 5): """Inits set of stacks with values in `arr` and max stack size""" self.stackset = Stack() self.length = 0 self.MAXSIZE = max_stack_size if arr: for val in arr: self.push(val)
def __init__(self, size, max_height): State.__init__(self) self.size = size self.max_height = max_height self.stones = [STONES[size][0] for _ in range(2)] self.capstones = [STONES[size][1] for _ in range(2)] self.board = [[Stack() for _ in range(size)] for _ in range(size)] self.history = set() self.turn = 1
def posteval(expr): operandstack = Stack() for i in expr.split(): if i in string.digits: operandstack.push(int(i)) else: sec = operandstack.pop() fis = operandstack.pop() res = eval('%d%s%d' % (fis, i, sec)) operandstack.push(res) return operandstack.pop()
def test_push(self): """ self.assertRaises fails when method doesn't throw mentioned error. Since, exception is handled, method push() doesn'throw error. Hence, assertRaises fails. Same with other below methods tests """ st = Stack() st.push(11) st.push(22) st.push(33) self.assertEqual(st.top(), 33) self.assertEqual(len(st), 3) st.push(44) st.push(55)
def eval_postfix(s): """Evaluates the postfix expression 's'.""" stack = Stack() s = s.split() for i in s: if operator(i) == False: stack.push(int(i)) else: b = stack.pop() a = stack.pop() result = evaluate(a, i, b) stack.push(result) return stack.pop()
def check(expr): s = Stack() index = 0 for i in expr: if i in '({[': s.push(i) elif i in ')}]': try: s.pop() except: return False if s.isEmpty(): return True else: return False
def rev_string(string): ''' Function rev_string Params: string Returns: the reverse of the input string ''' stack = Stack() rev = "" for letter in string: stack.push(letter) while not stack.is_empty(): rev = rev + stack.top() stack.pop() return rev
def eval_postfix(s): """Evaluates the postfix expression 's'.""" S=Stack() l=s.split(' ') i=0 while i!=len(l): symb=l[i] i=i+1 if not operator(symb): S.push(symb) else: a=S.pop() b=S.pop() result=apply(symb,a,b) S.push(result) return S.pop()
def move_top_k(self, r_orig, c_orig, r_dest, c_dest, k): assert 0 <= r_orig and r_orig < self.size and 0 <= c_orig and c_orig < self.size, 'move_top_k orig out of bounds r={0}, c={1}'.format( r_orig, c_orig) assert 0 <= r_dest and r_dest < self.size and 0 <= c_dest and c_dest < self.size, 'move_top_k dest out of bounds r={0}, c={1}'.format( r_dest, c_dest) assert 0 < k and k <= len(self.board[r_orig][ c_orig]), 'move_top_k number of pieces out of bounds k={0} and board has {1} pieces'.format( k, len(self.board[r_orig][r_dest])) tmp = Stack() for i in range(k): tmp.add(self.board[r_orig][c_orig].remove()) if len(self.board[r_dest][c_dest]) > 0: piece_type, owner = self.board[r_dest][c_dest].top() if piece_type == STANDING_STONE: self.set_top_piece(r_dest, c_dest, FLAT_STONE, owner) for i in range(k): self.board[r_dest][c_dest].add(tmp.remove())
def eval_prefix(expr): T = Stack() sp = expr.split() l = len(sp) - 1 while l >= 0: symb = sp[l] l = l - 1 if not operator(symb): T.push(symb) else: if T.isEmpty(): return False else: a = T.pop() b = T.pop() c = apply(a, b, symb) T.push(c) return T.pop()
def isMatched(expr): """Checks if the expression 'expr' has matching opening/closing symbols.""" S = Stack() for ch in expr: if ch in ('(', '[', '{'): S.push(ch) elif ch in ('}', ']', ')'): if S.isEmpty(): return False if matches(ch, S.topE()): S.pop() else: return False else: pass if S.isEmpty(): return True return False
def convert(expr): S = Stack() sp = expr.split() l = len(sp) - 1 while l >= 0: symb = sp[l] l = l - 1 if not operator(symb): S.push(symb) else: if S.isEmpty(): return False else: a = S.pop() b = S.pop() c = a + " " + b + " " + symb S.push(c) return S.pop()
def eval_prefix(strs): strs = reverse(strs) s = strs.split() St = Stack() count = 0 for value in s: value = reverse(value) if value in ['+', '-', '*', '/', '%']: b = St.Pop() a = St.Pop() if value == '+': result = a + b St.Push(float(result)) elif value == '-': result = a - b St.Push(float(result)) elif value == '/': result = a / b St.Push(float(result)) elif value == '*': result = a * b St.Push(float(result)) elif value == '%': result = a % b St.Push(float(result)) elif is_number(value): St.Push(float(value)) else: print("Error") return St.Top()
def conInfi(expr): sc = Stack() pexp = '' for ch in expr: if ch in ('*', '/', '+', '-'): while (sc.isEmpty() is False and Scale(sc.topE()) >= Scale(ch)): pexp += sc.pop() + ' ' sc.push(ch) elif ch == '(': sc.push(ch) elif ch == ')': while (sc.isEmpty() is False and sc.topE() is not '('): pexp += sc.pop() sc.pop() else: pexp += ch + ' ' while (not sc.isEmpty()): pexp += sc.pop() + ' ' return pexp
def isMatched(expr): """Checks if the expression 'expr' has matching opening/closing symbols.""" s = Stack() for char in expr: if char == '[' or char == '{' or char == '(': s.push(char) elif char == ']' or char == '}' or char == ')': if s.isEmpty(): return False else: symbol = s.peek() char = invert(char) print("Next char is: ", char) if symbol == char: s.pop() else: return False return True
def checking(list): stack = Stack() balanced = True index = 0 while index < len(list) and balanced: symbol = list[index] if symbol in '([{': stack.push(symbol) else: if stack.isEmpty(): balanced = False else: top = stack.pop() if not compare(top, symbol): balanced = False index = index + 1 if balanced and stack.isEmpty(): return True else: return False
def postfix(expr): optstack = Stack() olist = [] for i in expr.split(): if i is '(': optstack.push(i) elif i in string.uppercase or i in string.digits: olist.append(i) elif i is ')': while True: h=optstack.pop() if h == '(': break olist.append(h) elif i in prior.keys(): if not optstack.isEmpty(): if optstack.peek() == '(': optstack.push(i) else: while True: if not optstack.isEmpty(): if prior[i]>prior[optstack.peek()]: optstack.push(i) break else: olist.append(optstack.pop()) else: optstack.push(i) break else: optstack.push(i) if optstack: while not optstack.isEmpty(): olist.append(optstack.pop()) return ' '.join(olist)
def convert(expr): post = "" s = Stack() for i in range(len(expr) - 1, -1, -1): if isOperator(expr[i]) is True: #print(expr[i]) if s.isEmpty() is True: return "invalid expr" else: post += s.pop() if s.isEmpty() is True: return "invalid expr" else: post += s.pop() post += expr[i] s.push(post) #print(s.topE()) post = "" elif expr[i] is " ": pass else: s.push(expr[i]) #print(s.topE()) return s.topE()
def isMatched(expr): """Checks if the expression 'expr' has matching opening/closing symbols.""" sp = expr.split() b = 0 S = Stack() while b != len(sp): symb = sp[b] b = b + 1 if symb == '{' or symb == '[' or symb == '(': t = symb S.push(symb) elif symb == '}' or symb == ']' or symb == ')': if S.isEmpty(): return False else: left = S.pop() if not match(symb, left): return False return S.isEmpty()
def __init__(self): self.addstack = Stack() self.removestack = Stack()
def __init__(self, arr=None): """Inits stack with vals in `arr`""" self.stack = Stack() if arr: for val in arr: self.push(val)
from mystack import Stack #Finds whether given input paranthesis sequence is right or not.A stack application s = Stack() #((((()))))() def check(expr): s = Stack() index = 0 for i in expr: if i in '({[': s.push(i) elif i in ')}]': try: s.pop() except: return False if s.isEmpty(): return True else: return False print check('([{}])}')