How to define variable values using user input

只愿长相守 提交于 2020-01-25 08:39:16

问题


I have come across an issue I don't quite know how to solve. I'm trying to use solver to solve a simple equation. However, I want it so that you can solve for any variable you want, and give any value for the other constants that you want.

from sympy import *
a, b, c, d=symbols('a b c d')

constants=[]
input1=list(input('input variables for a,b,c,and d'))
for value in input1:
    try:    
        int_values=int(value)
        constants.append(int_values)
    except: 
        solve_for=value

equation=solveset(a + (b-1) * c-d, solve_for)
print (equation)

This is of course incomplete, because the values for a,b,c,and d aren't assigned. The way I have it setup so far, for input 1, if the user wants to solve for a variable, they simply type that variable name in, if they want to assign a value to the variable, they input the value of the variable. The issue comes down to, how can I set it up so the user can assign values to the constants table? I.E.

def_var_vale=list(input('define what variables are in constants'))
def_var_value[0],def_var_value[1],def_var_value[2]=constants[0],constants[1],constants[1]

The above doesn't work, but the logic is:

#input
def_var_value=[b, c, d]
constants=[1,2,3]
#desired output
b=1
c=2
d=3
# defined variables and their values to be used for the equation 

or another method, perhaps simpler/cleaner:

for letter,number in zip(def_var_value,constants):
      letter=number

or something of that similar nature. But of course, this doesn't define them either. I was thinking maybe you could create a dictionary, where a:1, b:2, and c:3, but at this point I'm just throwing ideas around and shooting in the dark. So any feedback would be greatly appreciated!


回答1:


I'm not sure but maybe this is what you want:

from sympy import *

a, b, c, d = syms = symbols('a b c d')
eq = a + (b-1) * c-d

constants=[]
input_string = '1 2 3 d'
input_words = input_string.split()
rep = {}
for word, sym in zip(input_words, [a,b,c,d]):
    if word.isalpha():
        solve_for = sym
    else:
        rep[sym] = int(word)

soln = solveset(eq.subs(rep), solve_for)

print(soln)

Basically we build up a dict and pass that to subs:

In [1]: (x + 2*y)                                                                                                                 
Out[1]: x + 2⋅y

In [2]: (x + 2*y).subs({x: 5})                                                                                                    
Out[2]: 2⋅y + 5


来源:https://stackoverflow.com/questions/59556573/how-to-define-variable-values-using-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!