fork download
  1. import re
  2. from collections import defaultdict
  3.  
  4. string = '-12.5e-1 x^3 + -5 x^2 --0.5x +-0.75x^3 +6'
  5.  
  6. pattern = re.compile(r'\s*([+-])\s*([-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?)\s*(x(\^\d+)?)?')
  7.  
  8. coefficients = defaultdict(int)
  9. string = '+' + string.rstrip()
  10. while string:
  11. match = pattern.match(string)
  12. if not match:
  13. raise ValueError('Invalid input starting with {}'.format(string))
  14. sign = 1 if match.group(1) == '+' else -1
  15. coefficient = sign * float(match.group(2))
  16. if match.group(3):
  17. exp = match.group(4)
  18. exp = 1 if exp is None else int(exp[1:])
  19. else:
  20. exp = 0
  21. coefficients[exp] += coefficient
  22. string = string[match.end():]
  23.  
  24. print (coefficients)
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
defaultdict(<class 'int'>, {0: 6.0, 1: 0.5, 2: -5.0, 3: -2.0})