Generating Strings of Equations

We have a list of coefficients [2, 0, 1, 5, -1], and a list of variables ['x', 'y', 'z', 's', 't']. Our goal is to obtain an equation in the form of a string '2x + z + 5s - t = 0'. Therefore, we need to assign the coefficients to the variables before adding '= 0', while adhering to equation writing conventions such that terms in the form of 1x are written as x, and terms with 0 coefficients are omitted.

This code uses f strings, strings methods and list comprehensions.

The expression [f"{values[i]}{unknowns[i]}" for i in range(len(values)) if values[i]!=0] is a list comprehension containing f-strings that assign coefficients to variables, provided the coefficient is not zero. Then, the join method combines all elements of this list comprehension, separated by a +, into a single string. At this stage, the string looks like 2x+1z+5s+-1t. Next, we use the replace method to replace any '+-' with '-', effectively joining adjacent terms. Finally, we use another replace method to transform terms of the form 1x into just x.

values = [2,0,1,5,-1]
unknowns=['x','y','z','s','t']
text = '+'.join([
    f"{values[i]}{unknowns[i]}" for i in range(len(values)) if values[i]!=0])
text=text.replace('+-','-')+'=0'
for unknown in unknowns:
    text=text.replace(f'1{unknown}',f'{unknown}')
print(text)

see more articles