lambda, var length keyword arg, map, reduce, filter decorator

 lambda 

Definition from library help section.

Lambdas
*******

   lambda_expr ::= "lambda" [parameter_list] ":" expression

Lambda expressions (sometimes called lambda forms) are used to create
anonymous functions. The expression "lambda parameters: expression"
yields a function object.  The unnamed object behaves like a function
object defined with:

   def <lambda>(parameters):
       return expression

See section Function definitions for the syntax of parameter lists.
Note that functions created with lambda expressions cannot contain
statements or annotations.

Background 

>>> def add(a,b):
...     return a+b
...
>>> print(add)
<function add at 0x000001D5BA8A2660>
>>>
>>> x = add #Copy reference to x 
>>> x(3,4) #Since both x and add contains same reference
7

What is add? 
 
Add is a reference variable referring to function object. 

What is the difference between add and add()?

add - reference/name referring to function object
add() - actual function call

Lambda - 

>>> x = lambda a,b : a+b # a,b are list of parameters and a + b is operation. 
>>> x(3,4) # function call
7

x holds reference of function object 

Point to be noted: It is similar to below
 
def <lambda>(parameters):
       return expression
 
Example - 

Suppose we want to square numbers in list and for this functionality we will be using lambda function. 

>>> def squares(num, funct): # funct will be lamda function
...     for e in num:
...             print(e,funct(e))
...
>>> squares([2,3,4,5],lambda a : a* a )
2 4
3 9
4 16
5 25
>>>

Recursive lambda expression

>>> s = lambda n: 1 if n==1 else n + s(n-1) # recursive n-1 call 
>>> s(10)
55
>>> s = lambda n: 1 if n==1 else n+ s(n-1)
>>> s(20)
210

Variable length keyword argument

def f1(*t): #tuple
    pass
def f1(**d): #dictionary
    pass 

>>> def show(**d):
...     for k,v in d.items():
...             print(k,v)
...
>>> show(a=10,b=20,c=30)
a 10
b 20
c 30
>>>

Here, we can pass dictionary elements as keyword argument. 

a,b,c becomes keys and 10,20,30 will be values. 

Higher order function ** 

#map, reduce and filter
#Higher order function takes function as an argument and returns a function

Definition from library: 

class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)
 |      Return state information for pickling.

Example: Here we are giving a lamda function and providing a list iterables

>>> x = map(lambda n : n*n , [1,2,3,4])
>>> x
<map object at 0x000001D5BA8ECB50> # returns map object which is an                                    # iterator that can be converted
>>> l = list(x)
>>> l
[1, 4, 9, 16]
>>>

Example 2: - Use map to determine prime numbers in a given list.

>>> def isprime(n):
...     for i in range(2,n):
...             if(n%i == 0):
...                     return False
...     else:
...             return True
...
>>> x = map(isprime,[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
>>> list(x)
[True, True, False, True, False, True, False, False, False, True, False, True, False, False, False]
>>>

Filter

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |
 |  Return an iterator yielding those items of iterable for which         function(item)
 |  is true. If function is None, return the items that are true.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)
 |      Return state information for pickling.
 |
 |  -----------------------------------------------------------------

We can filter only prime using below filter syntax for previous example. 

>>> x = filter(isprime,[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
>>> list(x)
[2, 3, 5, 7, 11, 13] # picks only Items which are True in iterable 
>>>

reduce

It's an accumulator function which gives single element after iteration.

Definition from library:

reduce(...)
        reduce(function, iterable[, initial]) -> value

        Apply a function of two arguments cumulatively to the items of a sequence
        or iterable, from left to right, so as to reduce the iterable to a single
        value.  For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
        ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
        of the iterable in the calculation, and serves as a default when the
        iterable is empty.

To use reduce, we need to import

>>> from functools import reduce
>>> r = reduce(lambda a,b:a+b,[1,2,3,4,5,6])
>>> print(r)

Decorators

Very important concept

Decorators are the higher order functions which takes function as an input and return a function. It is used to decorate existing function without changing the existing code. (Can be assumed like overriding) 

Advantage of using decorator

i) User experience is intact and will call function as required.
ii) Provides way to customize existing function without any changes to original one. If revert is required can be done just by removing decorator call.

Program 
#now add some authentication to check if valid user
def validate_user(UB_Funct):
    def Validate(data):
       
        #logic to validate user
        password = input("Enter your password")
        if password == "Income@123":
            print("Valid User : ")
            UB_Funct(data)
        else:
            print("Not authorised")
           
    return Validate
@validate_user
#program for decorator
#scenario to check user balance
def UserBalance(data):
    print("User balance is ",data)

UserBalance(10)

Comments