使用re.compile计算差分多项式的系数并在python中搜索

时间:2018-06-18 17:49:55

标签: python regex polynomials differentiation

测试多项式' 2x ^ 3 + 4x ^ 2 + 8x-16 '我的代码输出 [6,8] 作为微分多项式的系数。但是,输出应该是 [6,8,8] 为什么函数getNewCoefficients产生错误的结果?什么是产生正确结果的好方法?

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

2 个答案:

答案 0 :(得分:1)

使用负面的lookbehind断言可以更容易地解决这个问题。

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

此解决方案对x^x^-使用两个负面的后观(因为后面的内容必须是固定长度)。所以它写着“让我所有的整数都不在x^之前。

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

答案 1 :(得分:0)

您不需要re模块,您可以使用sympy模块,但必须先从http://www.sympy.org/en/index.html下载它。我不是sympy专家,但我找到了一个类似的Stack Overflow question,可以帮到你。

而且,只是为了让你知道,指数不算作系数......