How to calculate expression using sympy in python

前端 未结 5 1799
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 21:17

I need a calculate below expression using sympy in python?

exp = \'(a+b)*40-(c-a)/0.5\'

In a=6, b=5, c=2

5条回答
  •  难免孤独
    2020-12-08 21:44

    I realise this was already answered above, but in the case of getting a string expression with unknown symbols and needing access to those symbols, here is the code I used

    # sympy.S is a shortcut to sympify
    from sympy import S, Symbol
    
    # load the string as an expression
    expression = S('avar**2 + 3 * (anothervar / athirdvar)')
    
    # get the symbols from the expression and convert to a list
    # all_symbols = ['avar', 'anothervar', 'athirdvar']
    all_symbols = [str(x) for x in expression.atoms(Symbol)]
    
    # do something with the symbols to get them into a dictionary of values
    # then we can find the result. e.g.
    # symbol_vals = {'avar': 1, 'anothervar': 2, 'athirdvar': 99}
    result = expression.subs(symbols_vals)
    

提交回复
热议问题