Skip to content

Instantly share code, notes, and snippets.

@RamiAwar
Created November 17, 2018 19:38
Show Gist options
  • Save RamiAwar/edbf2b411240816b6601ee7d7f680d4e to your computer and use it in GitHub Desktop.
Save RamiAwar/edbf2b411240816b6601ee7d7f680d4e to your computer and use it in GitHub Desktop.
Polynomial-Derivative-Python Getting a polynomial's derivative using regex in python. ##How it works The input polynomial string is divided into an array of coefficients and an array of corresponding powers. Each coefficient is multiplied by the power and each power is decremented by one. (Simple derivativation) At the end the new coefficients a…
import re
def derivative(polynomial):
coefficient = re.findall(r'-?[\d]*[x$]', polynomial)
power = re.findall(r'[\^][-]?[\d$]+', polynomial)
derivative_polynomial = []
# print coefficient
# print power
for i in range(len(coefficient)):
coef = re.findall(r'[-\d]+',coefficient[i])
if len(coef) != 0:
if coef[0]=='-':
coef[0] = '-1'
a = int(coef[0])
else: a=1
b = 1
if i < len(power):
b = int(power[i][1:])
derivative = a*b
if b>2:
end = '^'+str(b-1)
elif b<0: end = '^' + str(b-1)
else: end=''
# print "a: " + str(a)
# print "b: " + str(b)
# sys.stdout.softspace=0
# print("+"*(derivative>0 and i!=0) +str(derivative)+ 'x'*(abs(b-1)>0)+end),
derivative_polynomial.append("+"*(derivative>0 and i!=0) + str(derivative)+ 'x'*(abs(b-1)>0)+end)
if len(derivative_polynomial)==0: derivative_polynomial.append('0')
return "".join(derivative_polynomial)
assert getDerivative("4x+1"),"4"
assert getDerivative("-4x-1"),"-4"
assert getDerivative("x^2+2x+1"),"2x+2"
assert getDerivative("0"),"0"
assert getDerivative("-100"),"0"
assert getDerivative("-x^2+3x+4"),"-2x+3"
assert getDerivative("-x^5-x^4-x^3"),"-5x^4-4x^3-3x^2"
assert getDerivative("10x^9+10x^3+10x"),"90x^8+30x^2+10"
assert getDerivative("100x^5+12x^3-3x-3"),"500x^4+36x^2-3"
assert getDerivative("-1000x^7+200x^4+6x^2+x+1000"),"-7000x^6+800x^3+12x+1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment