BlueHead
BlueHead

Reputation: 26

Python equation inputed by user

I'm trying to make some program which involves typing formulas in input by a user. My code for now looks like so:

import numpy as np
n = int(input('Dim = '))
g = np.zeros((n, n))
for a in range(0, n):
    print('Define the metric. \n g_', a, a,'=')
    metric_component = 'lambda x, y: ' + str(input())
    g[a, a] = eval(metric_component)
print(g)

I tried to search for answers but those i found didn't work. eval() function gives me error there: float() argument must be a string or a number, not 'function': sympify() gives basically the same "can't convert expression to float" Also i want to work on those constants not their numeric values, so i'm interesting to keep them through all program and have the final output expressed by them. Is it even possible?

Upvotes: 0

Views: 471

Answers (1)

smichr
smichr

Reputation: 19093

input() will return a string

>>> type(input())  # I type 1
1
<class 'str'>

So if you are expecting numeric input from the user and it can be non-integer, then just wrap the input with float. import numpy as np n = int(input('Dim = ')) g = np.zeros((n, n)) for a in range(0, n): print('Define the metric. \n g_', a, a,'=') g[a, a] = float(input()) print(g)

It's hard to tell what you want to be able to interpret from the user. If the user is going to give some expression of x and y and you are going to replace both those values with a you would either have to build a lambda that could be evaluated or do a substitution into a sympified expression:

>>> eval('(lambda x,y:'+'x + 2*y'+')(%s,%s)'%(a,a))
3*a
>>> sympify('x+2*y').subs(dict(x=a,y=a))
3*a

If you want the user to input expressions and then do something to them later, SymPy is ideally suited for this. Here, the user is prompted to fill items in a list and then those items are differentiated wrt x. It's just a toy example:

>>> from sympy import S  # shortcut for sympify
>>> from sympy.abc import x
>>> [S(input('?')) for i in range(2)]
?R**2
?R**2*sin(x)**2
[R**2, R**2*sin(x)**2]
>>> [i.diff(x) for i in _]
[0, 2*R**2*sin(x)*cos(x)]

Upvotes: 1

Related Questions