-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathequation.py
More file actions
61 lines (43 loc) · 1.31 KB
/
Copy pathequation.py
File metadata and controls
61 lines (43 loc) · 1.31 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
54
55
56
57
58
59
60
61
from math import sqrt
from typing import Optional
class Equation:
def __init__(self, a: int, b: int, c: int, v: str = "x") -> None:
self.a = a
self.b = b
self.c = c
self.v = v
def __str__(self) -> str:
contSign = "+"
coefSign = "+"
equation = f"{self.a}{self.v}² <sign_b> {abs(self.b)}{self.v} <sign_c> {abs(self.c)}"
if b < 0:
coefSign = "-"
if c < 0:
contSign = "-"
equation = equation.replace("<sign_b>", coefSign)
equation = equation.replace("<sign_c>", contSign)
return equation
@property
def canSolve(self) -> bool:
discriminant: int = self.b**2 - 4 * self.a * self.c
if discriminant < 0:
return False
else:
return True
def root(self) -> Optional[tuple[float, float]]:
if not self.canSolve:
return None
a = self.a
b = self.b
c = self.c
d = b**2 - 4 * a * c
root1 = (-b + sqrt(d)) / 2 * a
root2 = (-b - sqrt(d)) / 2 * a
return root1, root2
if __name__ == "__main__":
a, b, c = 3, 6, 67
equation = Equation(a, b, c)
if roots := equation.root():
print("Roots are", roots[0], roots[1])
else:
print("Eqn has no solution")