Question

I want to create many (more than 400) SymPy expressions using the same set of symbols. The expressions would look like:

z_1_8 = k1 + k2 + kuni + k4 + k7
z_2_9_0 = k2 + k8 + k1 + k6
z_3_1_10 = k3 + kbi + k2 + k7

The names 'z_1_8' would be generated from a list, where each member of the list contains the numbers that name each expression. Likewise the symbols would also come from a list in which each member contains a list of the symbols as strings - 'k1', 'k2' etc - for each expression to be generated.

list_to_generate_expression_names = [[1, 8], [2, 9, 0], [3, 1, 10],...]
list_to_generate_expressions = [['k1', 'k2','kuni','k4','k7'], ['k2', 'k8', 'k1', 'k6'], ['k3', 'kbi', 'k2', 'k7']]

What might be a way to do this?

Was it helpful?

Solution

I'm assuming here that every string in your list_to_generate_expressions is the name of an object that already exists. If that's the case, and your lists match up correctly, you can do this:

names = ['z_' + '_'.join([str(n) for n in name_nums]) for name_nums in list_to_generate_expression_names]
exprs = ['+'.join(expr_items) for expr_items in list_to_generate_expressions]

for name, expr in zip(names,exprs):
    exec('{0} = {1}'.format(name,expr))

Note that this does use exec, which should always be used cautiously, but since you're using your own lists it's perfectly safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top