Python:数学公式及其变量识别

时间:2016-11-02 06:33:15

标签: python variables math formula

我想编写一个识别数学公式的程序,并要求用户输入数值并显示结果。
  没有EVAL功能

  1. 程序必须识别4个变量。
  2. 程序必须识别算术运算符(+, - ,*,/,[^,()] - > extra)
  3. r = a(+, - ,*,/)b ..., - >得到方程式解析值,询问值并打印结果。
  4. 我现在拥有的是:

    formul=raw_input('Enter your formula: ")
    a=input("Value a: ")
    b=input("Value b: ")
    c=input("Value c: ")
    d=input("Value d: ")
    

2 个答案:

答案 0 :(得分:1)

这是一个很好的,你可以使用eval并在每次有NameError时捕获。像这样的东西

import re

variables = {}
formula = raw_input('Insert formula: ')
while True:
    try:
        res = eval(formula, variables)
    except NameError as e:
        v = re.match('name .(\w+). is not defined', e.message).group(1)
        variables[v] = input('insert value for %s: ' % v)
        continue
    print ("%s = %s" % (formula, res))
    break

输出类似于

Insert formula: me + you
insert value for me: 10
insert value for you: 100
me + you = 110

答案 1 :(得分:0)

formula=formula.replace("a", str(a)).replace("b",str(b)).replace("c", str(c)).replace("d", str(d))

print eval(formula)
相关问题