-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdifferentiate.py
More file actions
53 lines (49 loc) · 1.79 KB
/
differentiate.py
File metadata and controls
53 lines (49 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def differentiate(equation : str):
"""
equation will be a polynomial e.g. 3x^2+4x+2 or 3/4x^3+2x^2+5x+1/2
equation will have to be simplified e.g. 4x^2+3x+2 instead of 8x^5/2x^3+3x^2/x+2 and 4x^2+3x+2 instead of 6x^2-2x^2+8x-5x+2
"""
flag = False
result = ""
indflag = False
if not equation[0].isdigit():
equation = "1" + equation
if any([
equation[-1] == "x",
equation.split("^")[-1].isdigit(),
]):
equation += "+1"
equation = equation.split("x")
for i in equation:
if i=="":
continue
if i[1:].isdigit() and flag:
if i[0] == "^":
evaluated = str(eval(f"{coeff}*{i[1:ind]}"))+f"x^{int(i[1:ind])-1}" if (int(i[1:ind])-2) else str(eval(f"{coeff}*{i[1:ind]}"))+"x"
if i != equation[1] and evaluated[0] != "-":
evaluated = "+" + evaluated
result += evaluated
else:
result += coeff if coeff[0] == "-" else "+"+coeff
elif not flag:
coeff = i
flag = True
else:
try:
ind = i.index("+")
indflag = True
except:
ind = i.index("-")
evaluated = str(eval(f"{coeff}*{i[1:ind]}"))+f"x^{int(i[1:ind])-1}" if (int(i[1:ind])-2) else str(eval(f"{coeff}*{i[1:ind]}"))+"x"
if i != equation[1] and evaluated[0] != "-":
evaluated = "+" + evaluated
result+=evaluated
if not len(i[ind:])-1:
coeff = eval(f"0+{i[ind:]}1")
else:
coeff = i[ind+1:] if indflag else i[ind:]
return result
# 8x^5+4x^4+2x^3+8x^2+2x+1
# [8, ^5+4, ^4+2, ^3+8, ^2+2, +1]
# 7x^3 + 8x^2
# [7, ^3+8, ^2]