dadadude
asked on
local maximum in a list"python"
Is there a function to compute the local maximum in a list? while uing python
If you mean "How do I find the largest value contained within a list" Then the answer would be:
max(MyList)
So in Python 2.6:
print max(MyList)
would print the largest value contained within the list.
max(MyList)
So in Python 2.6:
print max(MyList)
would print the largest value contained within the list.
ASKER
well no i want to find a local maximum in a list of points like for example:
A = [1,4,9,2,10,4]
the local maximums in this list are 9 and 10 we define a local max point as : pi-1 < pi and pi+1 < pi.
i want to know if a function already exists it may be faster than a for loop.
A = [1,4,9,2,10,4]
the local maximums in this list are 9 and 10 we define a local max point as : pi-1 < pi and pi+1 < pi.
i want to know if a function already exists it may be faster than a for loop.
Whilst I can't answer absolutely (I don't know every function/method supplied by Python), I would be surprised to find an in-built function for this as it is not something that would be required often enough.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Try the following snippet. I guess that there is not any built-in function for that in standard modules. The functionality is too special for that.
The function can be easily improved to get generator that is capable to consume any sequence and return the values on the fly.
The function can be easily improved to get generator that is capable to consume any sequence and return the values on the fly.
def localMaxLst(lstIn):
if len(lstIn) == 0:
return [] # no results from empty list
lst = [] # init -- no results yet
m = lstIn[0] # the first element as the maximum...
candidate = True # ... candidate
for elem in lstIn[1:]: # through elements from the second one
if elem > m:
m = elem # better candidate
candidate = True
elif elem == m: # if equal, local maximum was lost
candidate = False
elif elem < m: # if lower then possible candidate to output
if candidate:
lst.append(m)
m = elem # start again...
candidate = False # being smaller it cannot be candidate
if candidate: # if the peak at the very end
lst.append(m)
return lst
lst = [1, 4, 9, 2, 10, 4]
print lst, '-->', localMaxLst(lst)
lst = [1, 4, 9, 9, 2, 10, 4, 11]
print lst, '-->', localMaxLst(lst)
lst = [12, 1, 4, 9, 9, 2, 10, 4, 11]
print lst, '-->', localMaxLst(lst)
Here is the generator solution that can consume the values on the fly.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
loool thank you Pepr! it's great.
thank you so much.
thank you so much.
Can you give us some context?