使用重新编译并在python中搜索来计算微分多项式的系数 [英] Calculating the coefficients of a differentiated polynomial using re.compile and searching in python

查看:92
本文介绍了使用重新编译并在python中搜索来计算微分多项式的系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

此解决方案对x^x^-使用两个负向后查找(因为向后查找必须为固定长度).因此,它显示为让我获得所有不带x^的整数.

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

这篇关于使用重新编译并在python中搜索来计算微分多项式的系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆