def pre2post(expr): expr = expr.split(" ") new_segement = "" while len(expr) != 1: for counter, char in enumerate(expr): if not counter < len(expr) - 2: break if char in operators.keys(): try: if not expr[counter + 1] in operators.keys(): if not expr[counter + 2] in operators.keys(): new_segement = expr[counter + 1] + " " new_segement = new_segement + expr[counter + 2] + " " + char for x in range(3): expr.pop(counter) except: print( "\n\n\tInvalid Prefix Expression, Try again with new Input" ) return [False, []] else: if new_segement: if counter != 0: expr = expr[:counter] + [new_segement ] + expr[counter:] else: expr = [new_segement] + expr new_segement = "" return [True, expr[0]]
def check_format(expr): global operators, expression_format if expr[0] in operators.keys(): exp_format = expression_format[0] elif expr[-1] in operators.keys(): exp_format = expression_format[2] else: exp_format = expression_format[1] print("\n\tExpression Format is ---> {}".format(exp_format)) return exp_format
def check_space(expr): expr_list = expr.split(" ") no_operators = True no_alnum = True for x in expr_list: if x in operators.keys(): no_operators = False if x.isalnum(): no_alnum = False if no_operators or no_alnum: return False if not all(char for char in expr_list): return False for c, x in enumerate(expr): if x == expr[-1]: continue if x.isspace() or expr[c + 1].isspace(): continue else: if x.isdigit() and expr[c + 1].isdigit(): continue else: return False return True
def post2in(expr): operand_list = [] expr = expr.split(" ") for char in expr: if char.isalnum(): operand_list.append(char) if char in operators.keys(): try: temp = "( " + operand_list[ -2] + " " + char + " " + operand_list[-1] + " )" except: print("\n\n\tOperand List empty, incorrect input") return [False, []] else: operand_list = operand_list[:-2] operand_list.append(temp) try: infix_expr = operand_list[0][1:-1].strip() except: print("\n\n\tInfix Can't be proccessed incorrect input") return [False, []] else: pass return [True, infix_expr]
def in2pre(expr): prefix = [] opstack = [] expr = expr[::-1] expr = expr.split(" ") for counter, char in enumerate(expr): if char == "(": expr[counter] = ")" elif char == ")": expr[counter] = "(" else: pass if char.isalnum(): prefix.append(char) elif char in operators.keys(): if not opstack: opstack.append(char) else: while opstack: last_item = opstack[-1] if last_item == ")": opstack.append(char) break elif operators[char] > operators[last_item]: opstack.append(char) break elif operators[char] == operators[last_item]: if not char == "*": opstack.append(char) break else: prefix.append(opstack.pop(-1)) opstack.append(char) break else: prefix.append(opstack.pop(-1)) opstack.append(char) break else: if char == ")": opstack.append(char) elif char == "(": while opstack[-1] != ")": prefix.append(opstack.pop(-1)) opstack.pop(-1) else: pass while opstack: prefix.append(opstack.pop(-1)) prefix = " ".join(prefix[::-1]) return [True, prefix]