I need to add two simple polynomials (represented as strings). The following example would clarify my requirement.
input1 = '5a+6b'
input2 = '2a+3b+9c'
The required sum should be as follows:
'7a+9b+9c'
Currently I have created a function (of 20 lines) to perform this task for me, but I think this can be improved.
EDIT: Adding my code
def add_domain_strings():
input_list = ['5a+6b', '2a+3b+9c']
vars_dict = {}
for input in input_list:
temp_list = input.split('+')
for i in temp_list:
split_index = None
for j in i:
if not j.isdigit():
split_index = i.index(j)
break
if i[split_index:] in vars_dict:
vars_dict[i[split_index:]] += int(i[:split_index])
else:
vars_dict[i[split_index:]] = int(i[:split_index])
sum_string = ''
for k,v in vars_dict.iteritems():
if sum_string:
sum_string += '+%s%s' % (v,k)
else:
sum_string += '%s%s' % (v,k)
return sum_string
sympy does close to what you want
>>> import sympy
>>> a,b,c = sympy.symbols('abc')
>>> 5*a+6*b + 2*a+9*b+9*c
7*a + 9*c + 15*b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With