I'm currently building a "formula editor" in a GUI application in python.
I use sympy to parse and check the validity of the typed formula, based on a dictionary of subs
. No problem with that.
Sometimes, user will need to type "complex" formulae with redundant parameters. See this example below:
Array([0.9, 0.8, 1.0, 1.1])[Mod(p-1, 4)]
The list [0.9, 0.8, 1.0, 1.1]
is chosen by the user and can be of any length. Given the value of p
variable, il will result in one of the four elements of the list. The number 4
is obviously len([0.9, 0.8, 1.0, 1.1]
.
The user can easily mistype the formula...
Rather, I would like to create my own function, eg. userlist()
, taking the list as argument and behaving as needed.
I have read this which helped me start with functions taking numbers as argument. It did not help me much with arguments which are lists.
Thank you in advance.
EDIT:
In a nutshell, I need to define userlist()
in some way so that this line
parse_expr("userlist(p, [8, 4, 6, 7])").evalf(subs={'p': 10})
returns the Mod(p-1, len(list))
th element of the list (here the 2nd element: 4
).
I'm not sure I understand what you're asking but maybe this helps:
In [75]: A = IndexedBase('A')
In [76]: A[Mod(p-1, 4)]
Out[76]: A[Mod(p + 3, 4)]
In [77]: f = lambdify((p, A), A[Mod(p-1, 4)])
In [78]: f(2, [3, 5, 6, 7])
Out[78]: 5