Reputation: 23
Can anyone suggest a method to get local min in a list?
For example, I have a list [50, 50, 49, 49, 49, 50, 50, 50, 49, 49, 49, 48, 48, 48, 47, 47, 48, 48, 13, 12, 11, 10, 11, 12]
.
I want to get the answer [49, 47, 10]
, and the index.
I had tried, but I get the answer like [49, 50, 47, 48, 10, 11, 12]
.
Can someone help me to revise the code?
Thanks a lot.
for i in range(len(list)):
if (i != 0) & (i+1 != len(list)):
if (list[i] == list[i + 1]):
repeat += 1
elif (list[i] < list[i - 1]):
repeat = 1
continue
elif (list[i] < list[i + 1]):
group_list.append(list[i])
Upvotes: 2
Views: 98
Reputation: 12417
Note: Please avoid using list
as a name for your list. list
is a predefined keyword in Python. You can use or
to check if you are at the beginning or end of the list and at the same time compare values to their left and right. Assuming your list name is l
, I think you want this:
mins = [x for i,x in enumerate(l) if ((i==0) or (l[i-1]>=x)) and ((i==len(l)-1) or (x<l[i+1]))]
output:
[49, 47, 10]
Upvotes: 0
Reputation: 619
You could loop through the list and find places where it changes from decreasing to increasing.
def local_minima(lst):
mins = []
decreasing = True
for i in range(len(lst) - 1):
a = lst[i]
b = lst[i + 1]
if not decreasing and b < a:
decreasing = True
elif decreasing and b > a:
mins.append(a)
decreasing = False
return mins
>>> local_minima([50, 50, 49, 49, 49, 50, 50, 50, 49, 49, 49, 48, 48, 48, 47, 47, 48, 48, 13, 12, 11, 10, 11, 12])
[49, 47, 10]
Upvotes: 1