Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string processing based on the numeric part: '5a+6b' + '2a+3b+9c' = '7a+9b+9c'

Tags:

python

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
like image 340
sidhshar Avatar asked Nov 29 '22 04:11

sidhshar


1 Answers

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
like image 91
John La Rooy Avatar answered Dec 05 '22 01:12

John La Rooy