Created
January 19, 2025 17:47
-
-
Save hbisneto/858e0e81a9098f10bb1f731ecaf1f2cd to your computer and use it in GitHub Desktop.
Expression.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from collections import defaultdict | |
def parse_expression(expression): | |
"""Converte a string de expressão em uma lista de termos com coeficientes e variáveis.""" | |
# Regex para capturar coeficientes e variáveis | |
pattern = r'([+-]?\d*)([a-zA-Z]+)' | |
terms = re.findall(pattern, expression) | |
parsed_terms = [] | |
for coef, var in terms: | |
coef = int(coef) if coef not in ("", "+", "-") else int(coef + "1") | |
parsed_terms.append((coef, var)) | |
return parsed_terms | |
def soma(expr1, expr2): | |
"""Soma duas expressões algébricas e retorna uma string simplificada.""" | |
# Parse as expressões | |
terms1 = parse_expression(expr1) | |
terms2 = parse_expression(expr2) | |
# Armazena os coeficientes dos termos | |
term_dict = defaultdict(int) | |
# Adiciona termos da primeira expressão | |
for coef, var in terms1: | |
term_dict[var] += coef | |
# Adiciona termos da segunda expressão | |
for coef, var in terms2: | |
term_dict[var] += coef | |
# Construi a expressão final simplificada | |
result = [] | |
for var, coef in sorted(term_dict.items(), key=lambda x: x[1], reverse=True): | |
if coef == 0: | |
continue # Ignora termos com coeficiente 0 | |
elif coef == 1: | |
result.append(f"+{var}") | |
elif coef == -1: | |
result.append(f"-{var}") | |
else: | |
result.append(f"{'+' if coef > 0 else ''}{coef}{var}") | |
# Transforma a lista em string e corrige o sinal inicial | |
result_expr = "".join(result) | |
return result_expr.lstrip("+") # Remove o "+" inicial, se tiver um | |
entrada1 = "a+b-c" | |
entrada2 = "d+e+c+a" | |
resultado = soma(entrada1, entrada2) | |
print(resultado) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment