Search code examples
pythonpython-3.xmathpolynomialspolynomial-math

splitting terms in a polynomial expression without external libraries like sympy


Say i inputted "1+2x+3x^2" or "1-2x+3x^2"

How do i make a function that splits and makes a list of each term like [1, 2x, 3x^2] or [1, -2x, 3x^2]. I have been stumped at this for a while, for now the function im using currently, seperates only at the "+" so to get a list like [1, -2x, 3x^2] i have to input "1+-2x+3x^2"

Note: I won't be using complex polynomials but simple looking ones that doesn't include parenthesis or fractions.


Solution

  • import re
    
    s = '1+2x^2-3x^-3'
    
    s = re.sub('\^-', 'neg', s) # trick to deal the negative powers
    print(s)
    s=s.replace('-','+-')
    s=s.replace('neg','-')
    sub = s.split('+')
    
    print(sub)
    

    This will split your negative power variables correctly.