0

I am currently working on taking a string containing a linear expression of the form mx + b and returning a list containing the slope (m) and vertical intercept (b) as float values.

The program works good if the string contains both m and b (i.e.; 5x+3). However, it doesn't work if the string just contains m (i.e.; 5x).

I get a

IndexError: list index out of range.  

I know what the issue is, but I guess I am still lacking the skills to correct it. I wanted to reach out to see what I could do to fix it.

def getLinearParameters(mx_plus_b):
    equation_values = mx_plus_b.split("+")
    m = equation_values[0][:-1]
    b = equation_values[1]
    return [float(m), float(b)]

print(getLinearParameters("5x"))
Red
  • 26,798
  • 7
  • 36
  • 58
ptandrews
  • 9
  • 1
  • 1
    Add a default value to your `b = …` line with https://stackoverflow.com/a/41387299/1707015 ? What should `b` be if it is missing? Zero? – qräbnö Dec 12 '20 at 13:49
  • 1
    how diverse is your set of inputs going to be? E.g.: `'-2.3e6 + 10.8z'`? In other words: spaces? Floating point numbers? Other variable names? – Pierre D Dec 12 '20 at 13:56
  • 1
    `y=42` would trip it up as well – Patrick Artner Dec 12 '20 at 14:01
  • 1
    You might want to read [parsing-math-expression-in-python-and-solving-to-find-an-answer](https://stackoverflow.com/questions/13055884/parsing-math-expression-in-python-and-solving-to-find-an-answer) for inspiration – Patrick Artner Dec 12 '20 at 14:01

3 Answers3

2

You need to put the code inside Try and add catch in case the exception occurred and handle it

try:
    #Statments
except IndexError:
    #Error occurred
    #Do something

In the except you can add a default Value for example.

octopus
  • 151
  • 1
  • 8
2

You can use try except. except catches the exception and handle the exception
Try like this:

def getLinearParameters(mx_plus_b):
    equation_values = mx_plus_b.split("+")
    m = equation_values[0][:-1]
    try:
        b = equation_values[1]
    except:
        b = 0
    return [float(m), float(b)]
print(getLinearParameters("5x"))
ppwater
  • 2,315
  • 4
  • 15
  • 29
2

Avoid using try - except blocks to fix an error, as that is a band-aid, not a proper solution. Instead, use an if - else statement:

def getLinearParameters(mx_plus_b):
    equation_values = mx_plus_b.split("+")
    m = equation_values[0][:-1]
    
    if len(equation_values) > 1:
        b = equation_values[1]
    else:
        b = 0
        
    return [float(m), float(b)]

print(getLinearParameters("5x"))
Red
  • 26,798
  • 7
  • 36
  • 58
  • +1 for band-aid. Where can I read more about that? On the other hand, I think try catch is okay, it's Python after all and not a Java philosophy? – qräbnö Dec 12 '20 at 14:10
  • 1
    @qräbnö Here is an article: https://towardsdatascience.com/do-not-abuse-try-except-in-python-d9b8ee59e23b – Red Dec 12 '20 at 14:17
  • Credits: https://stackoverflow.com/a/65208608/13552470 – Red Dec 12 '20 at 14:28