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?
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:
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]
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)]
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With