forked from kal179/Beginners-Python-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_roots.py
49 lines (39 loc) · 957 Bytes
/
find_roots.py
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
"""
How it works:
Thing is simple first we determine the variable in equation;
Then we iterate through given range by user or default range;
For each iteration we replace the variables in equation to the number;
At last we return the roots found;
"""
from string import ascii_letters
def find_variable(string):
splitted = string.split()
for i in splitted:
if (i in ascii_letters):
return i
else: continue
return None
# Input format for function:
# "z ** 2 + 97 * z + (-4)"
def find_roots(S, rng = [-10000, 10000]):
res = []
for v in range(rng[0], rng[1]):
try:
test_case = S.replace(find_variable(S), str(v))
except Exception as e:
print(e)
return ""
if (eval(test_case) == 0):
res.append(v)
else:
continue
if (len(res) == 0):
return None
return res
#testing
"""
test_str = "x ** 2 + 5 * x - 6"
result = find_roots(test_str, [-10, -2])
for i in result:
print("Root of the equation is {}".format(i))
"""