[英]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.