-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputor
More file actions
executable file
·212 lines (184 loc) · 6.78 KB
/
computor
File metadata and controls
executable file
·212 lines (184 loc) · 6.78 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/python3
import os
import re
import sys
import math
def check_equation_errors(equation):
allowed_characters = 'X^0-9+-=*'
if len(re.findall('[^X\^0-9\+-=\*]', equation)) > 0:
sys.stderr.write("[?] Invalid equation\n")
sys.stderr.flush()
sys.exit(1)
if equation.count('=') != 1:
sys.stderr.write("[?] Wrong number of characters '='\n")
sys.stderr.flush()
sys.exit(1)
def get_variable_coefficient(value):
if '*' not in value:
value = re.sub('X', '*X', value)
value = value.split('*')
if value[0] == '-' or value[0] == '':
coef = 1 if value[0] == '' else -1
else:
coef = float(value[0])
if value[1] == 'X':
var = 'X^1'
else:
var = value[1]
return(coef, var)
def calculate_reduced_form(equation):
right_side = 1
dic = {}
for i in equation:
if i == '=':
right_side = -1
continue
elif re.match(r'^\d+(\.\d+)?$', i):
coef = float(i)
var = 'X^0'
elif 'X' in i:
if '.' in i:
if len(re.findall(r'^[-]?[0-9]+[.][0-9]+[*]?[X][\^0-9]*$', i)) != 1:
sys.stderr.write("[?] Invalid equation\n")
sys.stderr.flush()
sys.exit(1)
else:
if len(re.findall(r'^[-]?[0-9]*[*]?[X][\^0-9]*$', i)) != 1:
sys.stderr.write("[?] Invalid equation\n")
sys.stderr.flush()
sys.exit(1)
coef, var = get_variable_coefficient(i)
if var in dic:
new = dic.get(var) + (float(coef) * right_side)
dic.update({var: new})
else:
dic.update({var: float(coef) * right_side})
dic = dict(sorted(dic.items(), key=lambda x: x[0]))
return(dic)
def ft_abs(x):
if x < 0:
return -x
else:
return x
def square_root(number, epsilon=1e-6):
guess = number / 2.0 # Initial guess
while ft_abs(guess * guess - number) > epsilon:
guess = (guess + number / guess) / 2.0
return guess
def parsing_equation(equation):
equation = equation.strip() # Remove leading/trailing whitespace
# TO-DO: Taking equation as input
if not equation:
sys.stderr.write("[?] Input can't be empty\n")
sys.stderr.flush()
sys.exit(1)
# TO-DO: Simplifying the equation
equation = re.sub(r'\s+', '', equation)
equation = re.sub(r'\b[-]', '+-', equation).replace('=', '+=+')
check_equation_errors(equation)
# TO-DO: Getting all values of the equation splited
equation = equation.split('+')
# TO-DO: Validating if the equation is valid or no
if equation.count(''):
sys.stderr.write("[?] Invalid equation\n")
sys.stderr.flush()
sys.exit(1)
return equation
def print_reduced_form(right_side, left_side):
# Step 4: Print the reduced form
reduced_terms = []
for power, coefficient in left_side.items():
if power in right_side:
right_coefficient = right_side[power]
right_side.pop(power)
else:
right_coefficient = 0
combined_coefficient = coefficient - right_coefficient
formatted_coefficients = [f"{combined_coefficient:.1f}" if combined_coefficient % 1 else str(int(combined_coefficient))]
term = f'{formatted_coefficients[0]} * X^{power}'
reduced_terms.append(term)
for power, coe in right_side.items():
formatted_coefficients = [f"{coe:.1f}" if coe % 1 else str(int(coe))]
reduced_terms.append(f'{formatted_coefficients[0]} * X^{power}')
reduced_equation = ' + '.join(reduced_terms)
print(f'Reduced form: {reduced_equation} = 0')
return reduced_terms
def check_equation_degree(reduced_equation):
# Create a list of keys with value 0
keys_to_remove = [key for key, value in reduced_equation.items() if value == 0]
# Remove the keys from the dictionary
for key in keys_to_remove:
reduced_equation.pop(key)
print(reduced_equation)
value = list(reduced_equation.keys())
power = int(re.sub(r'X[\^]', '', value[len(value) - 1]))
if power > 2:
print(f'Polynomial degree: {power}')
print(f'The polynomial degree is stricly greater than 2, I can\'t solve.')
exit()
def solve_first_equation(b, c):
print('Polynomial degree: 1')
if not b and not c:
print('Each real number is a solution')
elif b == 0 and c != 0:
print('The equation has no solutions')
elif b != 0:
print('The solution is:')
solution = float((-1) * c/b)
print(f'X0 = -1 * {c}/{b}')
print(f'{solution:.4f}')
return 0
def print_reduce_equation_form(equation):
formatted_terms = []
for term, coefficient in equation.items():
exponent = term.split('^')[1]
formatted_terms.append(f"{coefficient} * X^{exponent}")
formatted_equation = " + ".join(formatted_terms) + " = 0"
print("Reduced form: {0}".format(formatted_equation))
def solve_quadratic_equation(a,b,c):
print('Polynomial degree: 2')
solution = (b ** 2) - (4 * a * c)
if solution == 0:
print('Discriminant = 0')
print('The solution is: ')
print(f"X0 = -{b} / (2 * {a})")
print(f"X0 = {- b / (2 * a)}")
elif solution > 0:
sqt = square_root(solution)
x1 = (-b + sqt) / (2 * a)
x2 = (-b - sqt) / (2 * a)
print('Discriminant is strictly positive, the two solutions are:')
print(f"X1 = (-{b} + sqrt({solution})) / (2 * {a})")
print(f"X1 = {x1}")
print(f"X2 = (-{b} - sqrt({solution})) / (2 * {a})")
print(f"X2 = {x2}")
else:
sqt = square_root(-solution)
real_part = -b / (2 * a)
imag_part = sqt / (2 * a)
print('Discriminant is strictly negative, the two solutions are complex:')
print(f"real_part: -{b} / (2 * {a})")
print(f"imag_part: sqrt({-solution} / (2 * {a}))")
print(f'{real_part} + {imag_part} * i')
print(f'{real_part} - {imag_part} * i')
return 0
def solve_equation(equation_dic):
a = equation_dic.get('X^2') if 'X^2' in equation_dic else 0
b = equation_dic.get('X^1') if 'X^1' in equation_dic else 0
c = equation_dic.get('X^0') if 'X^0' in equation_dic else 0
if a == 0:
solve_first_equation(b,c)
else:
solve_quadratic_equation(a,b,c)
def main():
if len(sys.argv) > 1:
equation = sys.argv[1]
else:
equation = input("Enter equation: ").upper()
equation = parsing_equation(equation)
reduced_equation = calculate_reduced_form(equation)
print_reduce_equation_form(reduced_equation)
check_equation_degree(reduced_equation)
solve_equation(reduced_equation)
if __name__ == "__main__":
main()