繁体   English   中英

使用重新编译并在python中搜索来计算微分多项式的系数

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

在下面的代码中测试多项式' 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

使用否定的后向断言可以更轻松地解决此问题。

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

您不需要re模块,可以使用sympy模块,但是必须首先从http://www.sympy.org/en/index.html下载。 我不是一个sympy专家,但我发现了一个类似的堆栈溢出的问题 ,可以帮助你。

而且,只是让您知道,指数不算作系数...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM