developper.py

Created by frattini-fabrice

Created on June 28, 2024

2.82 KB


def parse_term(term):
    """Parse a single term like '3*x^2'."""
    term = term.replace(" ", "")  # Remove any spaces
    if '*' in term:
        coeff_part, var_part = term.split('*')
    else:
        if 'x' in term:
            if term.startswith('-'):
                coeff_part, var_part = term[0:2], term[2:]
            else:
                coeff_part, var_part = term.split('x')
                var_part = 'x' + var_part
        else:
            coeff_part, var_part = term, ''
    
    if '^' in var_part:
        var, power = var_part.split('^')
    else:
        var = var_part
        power = '1' if var_part else '0'
    
    coeff = int(coeff_part) if coeff_part not in ["", "-", "+"] else -1 if coeff_part == "-" else 1
    power = int(power)
    
    return (coeff, var, power)

def parse_expression(expr):
    """Parse an expression like '3*x^2 + 2*x - 1' into terms."""
    terms = []
    term = ''
    for char in expr:
        if char in '+-' and term:
            terms.append(term)
            term = char
        else:
            term += char
    terms.append(term)
    
    return [parse_term(term) for term in terms]

def expand(expr1, expr2):
    """Expand the product of two expressions."""
    terms1 = parse_expression(expr1)
    terms2 = parse_expression(expr2)
    
    result = {}
    
    for (c1, v1, p1) in terms1:
        for (c2, v2, p2) in terms2:
            if v1 == v2 or v1 == '' or v2 == '':
                var = v1 if v1 else v2
                power = p1 + p2
                coeff = c1 * c2
                if (var, power) in result:
                    result[(var, power)] += coeff
                else:
                    result[(var, power)] = coeff
    
    return result

def format_expression(terms):
    """Format the terms into a string expression."""
    formatted_terms = []
    for (var, power), coeff in sorted(terms.items(), key=lambda x: -x[1]):
        if power == 0:
            formatted_terms.append('{}{}'.format('+' if coeff >= 0 else '', coeff))
        elif power == 1:
            formatted_terms.append('{}{}*{}'.format('+' if coeff >= 0 else '', coeff, var))
        else:
            formatted_terms.append('{}{}*{}^{}'.format('+' if coeff >= 0 else '', coeff, var, power))
    return ' '.join(formatted_terms).replace('+ ', '+').replace('- ', '-')

def main():
    expr_input1 = input("Saisissez la première\nexpression algébrique\n(par exemple, x+1): ")
    expr_input2 = input("Saisissez la deuxième\nexpression algébrique\n(par exemple, x-2): ")
    
    # Normaliser les expressions saisies
    expr_input1 = expr_input1.replace("-", "- ")
    expr_input2 = expr_input2.replace("-", "- ")
    
    expanded_terms = expand(expr_input1, expr_input2)
    expanded_expr = format_expression(expanded_terms)
    
    print("Expression développée :\n{}".format(expanded_expr))

main()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.