Reputation: 516
I am trying to feed values into lambda and if values exceed a certain limit consecutively 5 times I want to return 1 from the function, I am using filter but each time the if
statement executes. How should I implement it using lambda? Please any other suggestion.
rpm = [45,20,30,50,52,35,55,65]
rpm_limit=45
def check():
x, i = 0, 0
while i < len(rpm):
if (filter(lambda x: x > rpm_limit, rpm)): # rpm values will be feeded continuously
x=x+1
print("RPM: ",rpm[i])
if x >= 5:
return 1
else:
x=0
i += 1
return 0
print(check())
Upvotes: 0
Views: 2643
Reputation: 2921
If you're dead set on using a lambda expression, I think reduce
is better suited to your purposes.
def check():
max_consec = reduce(lambda acc, r: acc + 1 if r > rpm_limit else 0, rpm, 0)
return 1 if max_consec >= 5 else 0
Here's what's going on: acc
gets incremented every time an rpm exceeds the max and set to 0 whenever it doesn't. This gives us the longest streak of over-the-max rpms, which we use to decide if we return a 1 or a 0.
EDIT: for python 3, you'll need to import reduce
from functools
. See demo for example.
EDIT2: Corrected some faulty logic. In this new example, acc
will contiune to be incremented if the max streak length has been met, so the end predicate is true whenever the max streak length has been exceeded. See demo link above for live example.
def check():
max_consec = reduce(
lambda acc, r: acc + 1 if (r > rpm_limit or acc >= max_streak) else 0, rpm, 0)
return 1 if max_consec >= max_streak else 0
Upvotes: 1
Reputation: 18136
Isn't that what you want ? Without filter and lambda, you could create a new list of 0/1 (1 if the limit is exceeded). After that you simply need to sum it up:
rpm = [45,20,30,50,52,35,55,65]
rpm_limit=45
def check():
exceedLimit = [1 if x > rpm_limit else 0 for x in rpm]
return sum(exceedLimit)
print('RPM exceeded the limit %s times' % check())
Returns:
RPM exceeded the limit 4 times
Upvotes: 0