if you are willing to sacrifice a little speed for massive control gain, I would suggest regular expressions:
from re import findall def make_poly(s): m = findall('([+-]?[0-9.]+)([az]+)', s) return dict([(i[1], float(i[0])) for i in m]) def add_polys(*polys): res = {} for poly in polys: for item in poly.iteritems(): if res.has_key(item[0]): res[item[0]] += item[1] else: res[item[0]] = item[1] return res >>> p1 = make_poly('4x+7y+3.5z') >>> p1 {'y': 7.0, 'x': 4.0, 'z': 3.5} >>> p2 = make_poly('-2x+1y+0.2z') >>> p2 {'y': 1.0, 'x': -2.0, 'z': 0.2} >>> >>> add_polys(p1, p2) {'y': 8.0, 'x': 2.0, 'z': 3.7}
Some switching is still required for cross frames and incorrect user input, but it still works
source share