Search code examples
pythonregexpolynomialsdifferentiation

Calculating the coefficients of a differentiated polynomial using re.compile and searching in python


Testing the polynomial '2x^3+4x^2+8x-16' my code below outputs [6, 8] as the coefficients of the differentiated polynomial. However, the output should be [6, 8, 8]. Why is the function getNewCoefficients producing the wrong result? What would be a good way to produce the correct result?

def getNumbers(polynomial):
    regex = re.compile(r"[+-]?\d+(?:\.\d+)?")
    return  regex.findall(polynomial)

def formatNumbers(numbers):
    formattedNumbers = []
    for e in numbers:
        if (e[0] == '+'):
            formattedNumbers.append(e[1:])
        else:
            formattedNumbers.append(e)
    return formattedNumbers

def getNumberPositions(polynomial, numbers):
    numberPositions =  []
    for e in numbers:
        tmp = [m.start() for m in re.finditer(e, polynomial)]  
        for f in tmp:
           if f not in numberPositions:
                numberPositions.append(f)
    return sorted(numberPositions)

def getNewCoefficients(polynomial, numberPositions, numbers):
    tmp = '0'
    newCoefficients = []
    for i in range(0,len(numberPositions)):
        if numberPositions[i] + 1 < len(polynomial):
            if polynomial[numberPositions[i] + 1] == '+' or polynomial[numberPositions[i] + 1] == '-':
                newCoefficients.append(int(numbers[i])*int(tmp))
        elif numberPositions[i] - 1 > 0:
            if polynomial[numberPositions[i] - 1] == '+' or polynomial[numberPositions[i] - 1] == '-':
                newCoefficients.append(int(numbers[i]))
        tmp = numbers[i]
    return newCoefficients

Solution

  • This problem can be solved much more easily using negative lookbehind assertions.

    COEFFICIENT_PATTERN = re.compile(r"(?<!x\^)(?<!x\^-)-?\d+")
    coefficients = [int(c) for c in COEFFICIENT_PATTERN.findall(polynomial)]
    

    This solution uses two negative lookbehinds for x^ and x^- (because look behinds must be fixed length). So it reads "get me all integers not preceded by x^.

    >>> COEFFICIENT_PATTERN.findall('2x^3+4x^2+8x-16')
    ['2', '4', '8', '-16']