Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Slope (given two points find the slope) -answer works & doesn't work;

Trying to figure out the function to return the slope of a line in Python. Problem directions are to find the slope of m with the slope coordinates given. Read through several other stack overflow posts, but none seem to make a working solution. Here are a variety of the variations I've tried:

def slope(x1, y1, x2, y2):
    m = 0
    b = (x2 - x1)
    d = (y2 - y1)
    if b != 0:
        m = (d)/(b) 

    return m

slope(2, 3, 6, 7)


def slope(x1, y1, x2, y2):
    m = 0
    a = float(x1)
    b = float(x2)
    c = float(y1)
    d = float(y2)
    m = (d-c)/(b-a)
    return m
slope(2, 3, 6, 7)

def slope(x1, y1, x2, y2):
    m = ''
    a = float(x1)
    b = float(x2)
    c = float(y1)
    d = float(y2)
    m = (d-c)/(b-a)
    return m

slope(2, 3, 6, 7)



def slope(x1, y1, x2, y2):
    m = 0
    b = (x2 - x1)
    d = (y2 - y1)
    if b == 0:

        m = None

    else: 

        m = (d)/(b) 

    return m


slope(2, 3, 6, 7)

def slope(x1, y1, x2, y2):
    m = (y2-y1)/(x2-x1)
    return m

slope(2, 3, 6, 7)

At one point, I received error messages regarding a global m. I also tried making a " m = 0 " outside the function, but that didn't help. Also received "AssertionError: 0 != 1"

I've gotten the right answer followed by a second line =>None and when submitting the system says that it is not correct.

like image 559
Megan Avatar asked Jan 04 '17 11:01

Megan


People also ask

How do you find the slope between two points in Python?

You can find the line's slope using the linregress() function if we define the x and y coordinates as arrays. The following code uses the linregress() method of the SciPy module to calculate the slope of a given line in Python.

How do you find the slope when given two points of a slope?

Use the slope formula to find the slope of a line given the coordinates of two points on the line. The slope formula is m=(y2-y1)/(x2-x1), or the change in the y values over the change in the x values. The coordinates of the first point represent x1 and y1.


1 Answers

Your math is spot on, so that's not the problem. I tested all of your functions by adding print statements, and they all correctly returned 1.0.

Does your system require that you print out the returned value? Do this.

def slope(x1, y1, x2, y2):
    m = (y2-y1)/(x2-x1)
    return m

print slope(2, 3, 6, 7)

You can even optimize a bit more by leaving out the variable and directly returning your calculation, like this:

def slope(x1, y1, x2, y2):
    return (y2-y1)/(x2-x1)
like image 182
coralvanda Avatar answered Sep 21 '22 03:09

coralvanda