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

。_饼干妹妹 提交于 2019-12-24 23:07:49

问题


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

回答1:


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']



回答2:


You don't need the re module, you can use the sympy module, but you have to download it first from http://www.sympy.org/en/index.html. I'm not a sympy expert, but I found a similar Stack Overflow question that may help you.

And, just to let you know, exponents does not count as coefficients...



来源:https://stackoverflow.com/questions/50914959/calculating-the-coefficients-of-a-differentiated-polynomial-using-re-compile-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!