Skip to content

Instantly share code, notes, and snippets.

@Exoutia
Last active August 23, 2022 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Exoutia/fa1df862e2fc84c41caf2701b9357dec to your computer and use it in GitHub Desktop.
Save Exoutia/fa1df862e2fc84c41caf2701b9357dec to your computer and use it in GitHub Desktop.
First order derivation of standard algebraic polynomial in python
import re
x = "x**4 + 33*x**3 - 23*x**2 + 2*x + 1"
def first_order(x):
res = ''
for sign, coef, expo in re.findall("([\+-]?)\s?(\d+?)?\*?x\*?\*?(\d?)", '+' + x):
if coef == "":
coef = "1"
coef = int(sign + coef)
if expo == "":
expo = "1"
expo = int(expo)
print(sign, coef, expo)
new_coef = coef * expo
new_expo = expo - 1
if new_coef > 0:
res += '+'
if new_expo == 0:
res += f"{new_coef}"
elif new_expo == 1:
res += f"{new_coef}*x"
else:
res += f"{new_coef}*x**{new_expo}"
if res[0] == "+":
res = res[1:]
res = res.replace("+", " + ")
res = res.replace("-", " - ")
return res
mel = first_order(x)
print(mel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment