└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # fundamental-concept-in-chemistry 2 | balancing chemical equations. This program will allow you to input a chemical equation and it will output the balanced equation. The code uses the sympy library to solve the system of linear equations that represents the conservation of mass for each element. 3 | pip install sympy 4 | import sympy as sp 5 | 6 | def parse_compound(compound): 7 | """Parses a chemical compound into its elements and their counts.""" 8 | import re 9 | elements = re.findall(r'([A-Z][a-z]*)(\d*)', compound) 10 | return {el: int(num) if num else 1 for el, num in elements} 11 | 12 | def parse_side(side): 13 | """Parses a side of the equation (either reactants or products).""" 14 | compounds = side.split(' + ') 15 | compound_dicts = [parse_compound(compound) for compound in compounds] 16 | all_elements = set(el for compound in compound_dicts for el in compound) 17 | return compounds, compound_dicts, all_elements 18 | 19 | def balance_equation(equation): 20 | """Balances a chemical equation.""" 21 | left_side, right_side = equation.split(' -> ') 22 | left_compounds, left_dicts, left_elements = parse_side(left_side) 23 | right_compounds, right_dicts, right_elements = parse_side(right_side) 24 | 25 | all_elements = left_elements.union(right_elements) 26 | compounds = left_compounds + right_compounds 27 | 28 | # Create the system of equations 29 | equations = [] 30 | for element in all_elements: 31 | equation = sum(compound.get(element, 0) * sp.Symbol(f'x{i}') 32 | for i, compound in enumerate(left_dicts)) - \ 33 | sum(compound.get(element, 0) * sp.Symbol(f'x{i + len(left_dicts)}') 34 | for i, compound in enumerate(right_dicts)) 35 | equations.append(equation) 36 | 37 | # Solve the system of equations 38 | symbols = [sp.Symbol(f'x{i}') for i in range(len(compounds))] 39 | solution = sp.solve(equations, symbols, dict=True) 40 | if not solution: 41 | return "No solution found. The equation might be impossible to balance." 42 | 43 | # Convert the solution to integers 44 | coeffs = [solution[0][symbol].as_numer_denom()[0] for symbol in symbols] 45 | lcm = sp.lcm([coeff.denominator for coeff in coeffs]) 46 | coeffs = [coeff * lcm for coeff in coeffs] 47 | 48 | # Format the balanced equation 49 | balanced_left = ' + '.join(f'{coeff} {compound}' for coeff, compound in zip(coeffs[:len(left_compounds)], left_compounds)) 50 | balanced_right = ' + '.join(f'{coeff} {compound}' for coeff, compound in zip(coeffs[len(left_compounds):], right_compounds)) 51 | return f'{balanced_left} -> {balanced_right}' 52 | 53 | # Example usage 54 | equation = input("Enter a chemical equation to balance (e.g., H2 + O2 -> H2O): ") 55 | balanced_equation = balance_equation(equation) 56 | print("Balanced equation:", balanced_equation) 57 | --------------------------------------------------------------------------------