Skip to content Skip to sidebar Skip to footer

How To Implement A Counter Using A Lambda?

Can I implement a counter using a lambda function in python or some expression more pythonic? Here is my code: counter = 0 if 0 < arrival_time: counter += 1 else: pas

Solution 1:

Both x+=1 and pass are statements, but lambda is an expression, and you can't put statements inside an expression.

But that's fine.

lambda and def both just create a function, in the same way, but lambda is more limited.

If you need to create a function in the middle of an expression, you have to use lambda—but that's not the case here, since you're creating it just to use in an assignment statement.

If there's no good name for a function, you may want to use lambda, but that's not the case here either, because you're immediately giving it a name.

Some people (mostly those who've spent too much time with Lisp- or ML-family functional languages) also like to use lambda to make it clear that they're writing a "pure function", one that has no side effects and returns a value that depends only on the value of its parameters. But that's not the case here either. (If you changed it to lambda x, arrival_time: x+1 if 0 < arrival_time else x, that would be a good example of a pure function. You'd then call it with, e.g., x = count_late(x).)

So, there's absolutely no reason to use lambda here in the first place. Just use def:

def count_late(x, arrival_time):
    if 0 < arrival_time:
        x += 1

However, it's worth noting that, while this is now valid syntax, it isn't going to do any good.

Numbers are immutable; there's no way to change the number 2 into the number 3, because that would break all of physics. When you write x += 1, that just makes the local variable x into a name for the number 3 instead of a name for the number 2. If you call it with count_late(spam, 5) it's not going to change what spam means, just as if you call it with count_late(2*3, 5) it's not going to change what 2*3 means.

So, you probably wanted to:

  • Make this a pure function that returns a value (as mentioned above, this would mean you could use lambda, and some people would be happy with that, but I'd still definitely prefer def here), or
  • Make it a method of some object that has a self.x, or
  • Make x a global.

Solution 2:

if you have a function counter_late() :

**
#the 'counter' is in counter_late() or  global
counter_late((lambda arrival_time: counter+1 if 0 < arrival_time else PASS), 10)

**

else :

**
counter = 0 #global variable

counter = (lambda arrival_time: counter+1 if 0 < arrival_time else PASS)(10)

#check the value of counter 
print('conter=',counter)
**

10 is a variable what you want for a value of arrival_time.

if you get a syntax err.

PASS is change other value, you want to a number or condition.

for eg)

counter = (lambda arrival_time: counter+1 if 0 < arrival_time else 1)(0)


Post a Comment for "How To Implement A Counter Using A Lambda?"