Python, Regex: Cannot get coefficients from the equation(s)

Question:

I am trying to get coefficients from this equation using regex and later multiple equations:

2a+3b=c

However I get this annoying error. I checked my code and everything looks fine for me. This is the error:

AttributeError: 'int' object has no attribute 'group'

Here is my code:

import re

all_coefficients = []

def equation_solver(*equations):
    for equation in equations:
        sides = equation.split('=')
        coefficients = []
        for side in sides:
            terms = re.split(r"+", side)
            for term in terms:
                coefficient = re.match(r"d", term)
                if coefficient == None:
                    coefficient = 1
                coefficients.append(int(coefficient.group(0)))
        all_coefficients.append(coefficients)


equations = []

while True:
    equations.append(input())
    if input() == 's':
        break

equation_solver(*equations)

Thanks in advance

Asked By: ss3387

||

Answers:

It’s causing the error because re.match did not find any coefficient in the term c so if it didn’t find any coefficient (read carefully) you assigned the coefficient value as 1 BUT you cannot use group now because coefficient is an integer now!! So you use group function before you convert it to an integer, and it will look something like this:

import re

all_coefficients = []

def equation_solver(*equations):
    for equation in equations:
        sides = equation.split('=')
        coefficients = []
        for side in sides:
            terms = re.split(r"+", side)
            for term in terms:
                coefficient = re.match(r"d", term)
                if coefficient == None:
                    coefficient = 1
                else:
                    coefficient = coefficient.group(0) # Use group beforehand
                coefficients.append(int(coefficient))
        all_coefficients.append(coefficients)


equations = []

while True:
    equations.append(input())
    if input() == 's':
        break

equation_solver(*equations)

Hope this helps

Answered By: nobody849237
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.