栈 后缀表达式
看了老师给的博客,学习了一下,我学的确实很菜啊,仿照写了一个可以实现任意数字个数的加括号运算,目前只支持加一个括号。。。。
收获真的挺大
def to_rpn(f4): def compare(x, y): v = {'+': 0, '-': 0, '*': 1, '/': 1, '(': 2} return 1 if y == '(' else v[x] - v[y] rpn, operators = [], [] for i in f4: if i not in ['+', '-', '*', '/', '(', ')']: rpn.append(i) else: if i == ')': while operators[-1] != '(': rpn.append(operators.pop()) operators.pop() elif not operators or 0 < compare(i, operators[-1]): operators.append(i) else: while operators and compare(i, operators[-1]) < 1: rpn.append(operators.pop()) operators.append(i) while operators: rpn.append(operators.pop()) return rpn def rpn_to_answer(f4): answer_func = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y] answer_func_re = [lambda x, y: y + x, lambda x, y: (y - x) * -1, lambda x, y: y * x] number = [] for i in f4: if i not in ['+', '-', '*', '/']: number.append(i) else: x, y, z = number.pop(), number.pop(), None try: z = answer_func[['+', '-', '*', '/'].index(i)](y, x) except TypeError: z = answer_func_re[['+', '-', '*', '/'].index(i)](y, x) number.append(z) return number[0] def random_f4(_op):#操作数 from random import randint as ran r = [] j = _op*2 - 1 for i in range(j): if i % 2 == 1: r.append(['+', '-', '*', '/'][ran(0, 3)]) if i % 2 == 0: r.append(ran(1, 9)) x = ran(0,_op-2) r.insert(x*2,'(') y = ran(x+2,_op) r.insert(y*2,')') return (r) if __name__ == "__main__": from fractions import Fraction as F ops = input("数字个数:") ops = int(ops) r = random_f4(_op=ops) print(r) r = to_rpn(r) print(r) r = rpn_to_answer(r) r = F(r).limit_denominator(1000) print(r)
截图:
现在python学的还是很菜啊。。。。。。。。。