Mechanic Mechanic - 5 months ago 30
Python Question

Find the points with the steepest slope python

I have a list of float points such as

[x1,x2,x3,x4,....xn]
that are plotted as a line graph. I would like to find the set of points where the slope is the steepest.

Right now, Im calculating the difference between a set of points in a loop and using the
max()
function to determine the maximum point.

Any other elegant way of doing this?

Answer

Assuming points is the list of your values, you can calculate the differences in a single line using:

max_slope = max([x - z for x, z in zip(points[:-1], points[1:])])

But what you gain in compactness, you probably lose in readability.

What happens in this list comprehension is the following:

  • Two lists are created based on the original one, namely points[:-1] & points[1:]. Points[:-1] starts from the beginning of the original list and goes to the second to last item (inclusive). Points[1:] starts from the second item and goes all the way to the last item (inclusive again.)

Example

example_list = [1, 2, 3, 4, 5]
ex_a = example_list[:-1]  # [1, 2, 3, 4]
ex_b = example_list[1:]   # [2, 3, 4, 5]
  • Then you zip the two lists creating an object from which you can draw x, z pairs to calculate your differences. Note that zip does not create a list in Python 3 so you need to pass it's return value to the list argument.

Like:

example_list = [1, 2, 3, 4, 5]
ex_a = example_list[:-1]  # [1, 2, 3, 4]
ex_b = example_list[1:]   # [2, 3, 4, 5]
print(list(zip(ex_a, ex_b)))  # [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
  • Finally, you calculate the differences using the created pairs, store the results in a list and get the maximum value.

If the location of the max slope is also interesting you can get the index from the created list by using the .index() method. In that case, though, it would probably be better to save the list created by the comprehension and not just use it.