Higher order functions and closures - 1 - Hands On

Python Python Function (Article) Python Function (Program)

997

1. Higher order functions and closures - 1

• Define a function named detecter with one parameter element, which returns an inner function is In.

⚫ isIn accepts a parameter sequence, and returns True or False after checking the presence of element in sequence.

• Create two closure functions detect30 and detect45 using detecter. • Pass 30 to detect30, and 45 to detect45 for implementation.

• Use the 'Test against custom input' box to output the result for debugging. Provide a set of integers separated by comma (refer test case samples) to display the output/error.

Given Input:

2,30,45,6

Expected Output:

True
True

Code Hint:

 #!/bin/python3

import sys
import os



#Write detecter implementation

    #Write isIn implementation    

#Write closure function implementation for detect30 and detect45

if __name__ == "__main__":
    with open(os.environ['OUTPUT_PATH'], 'w') as fout:
        func_lst = [detect30, detect45]
        res_lst = list()
        lst = list(map(lambda x: int(x.strip()), input().split(',')))
        for func in func_lst:
            res_lst.append(func(lst))
        fout.write("{}\n{}".format(*res_lst))

Program:

 #!/bin/python3
import sys
import os

#Write detecter implementation
    #Write isIn implementation    
#Write closure function implementation for detect30 and detect45

def detector(element):
    e=element
    def isIn(sequence):
        a=0
        for i in sequence:
            if int(i)==e:
                a=1
        if a==1:
            return True
        else:
            return False
    return isIn
detect30 = detector(30) # 'c1' is a clousure
detect45 = detector(45) # 'c2' is a clousure


if __name__ == "__main__":
    with open(os.environ['OUTPUT_PATH'], 'w') as fout:
        func_lst = [detect30, detect45]
        res_lst = list()
        lst = list(map(lambda x: int(x.strip()), input().split(',')))
        for func in func_lst:
            res_lst.append(func(lst))
        fout.write("{}\n{}".format(*res_lst))

Output:

 True
True

Explanation:

Text case Input:

8,30,4,6

Text case Output:

True
False

Text case 2 Input:

8,3,4,6,9,4,5,0,1,445,300

Text case 2 Output:

False
False

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.