Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the points with the steepest slope python

Tags:

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?

like image 577
Raja Sattiraju Avatar asked Mar 13 '26 20:03

Raja Sattiraju


2 Answers

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.

like image 183
Ma0 Avatar answered Mar 15 '26 08:03

Ma0


Numpy has a number of tools for working with arrays. For example, you could:

import numpy as np

xx = np.array([x1, x2, x3, x4, ...])  # your list of values goes in there
print(np.argmax(xx[:-1] - xx[1:]))  # for all python versions
like image 23
VBB Avatar answered Mar 15 '26 10:03

VBB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!