python1-1

High Order functions

A high order function is a function that operates on other functions, either by taking a function as it argument or by returning a function.

map(function, iterable)

Returns an iterator that applies function to every item of iterable

# map example

names = ['john', 'jane', 'jersey', 'jannie']

# capitalize func gets applied on each name of list
for name in map(str.capitalize, names):
    print(name)

Output:
-------- 
John
Jane
Jersey
Jannie

filter(function, iterable)

Constructs an iterator from those elements of iterable for which function returns true

# filter example

sales_amount = [500, 600, 700, 900, 1500, 2100]

# filter and select only those sales which are more than 1000
high_sales = lambda s : s > 1000

for s in filter(high_sales, sales_amount):
    print(s)

Output
-------
1500
2100

functools module

functools module : The functools module is for higher-order functions

functools.partial(func, args, *kwargs)

Returns a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.

from functools import partial
# partial : example 

base_two = partial(int, base=2)
base_two.__doc__ = 'Converts base 2 string to int'

print(f"Integer value of binary : '10010' is {base_two('10010')}")

Integer value of binary : '10010' is 18

functools.reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

from functools import reduce

# reduce exampe

# sum of first n integers

def total_n(n):
    nums = list(range(1, n+1))
    total_nums = reduce(lambda x , y: x + y, nums)
    return total_nums

print(total_n(10)); # sum of first 10 integers

print(total_n(20)); # sum of first 20 integers

Output:
-------
55
210
## An example to use all high order functions described above

# task to find all positive sales, add a commission of 10 percent and calculate total amount

sales_amount = [100, 200, 300, -80, 500, -90]  

# lambda func to select only positive no..
get_positive = lambda x : x > 0

filtered_sales = list(filter(get_positive, sales_amount))

# lambda fun to calculate comm and add to sales amount
calc_comm = lambda comm, sal : comm * sal + sal

# partial func to set sales comm at 10% 
sales_comm = partial(calc_comm, 0.10)

sales_with_comm = list(map(sales_comm, filtered_sales))

# lambda to calculate total amount
total = lambda x, y: x + y

total_amt = reduce(total, sales_with_comm)
print(total_amt)

Output:
1210.0

Shekhar Pandey

Add comment