Creating own Reduce and Filter Function In Python
Basic ideas about working of loops and functions
1. Creating
myreduce()
function
Reduce function is an inbuilt function in python whose major task is to give aggregate value as an output. Syntactically it is written as;
reduce(func,iter_obj)
here reduce operation will be done on “func” function and “iter_obj” is implying the iterable data values used to return result of output.
reduce()
function takes only iterable data to give output other than iterable data will cause error in output (gives no output).
# Method I
from functools import reduce
def sum(a,b):
return a+b
list_1=[10,15,25,10,40)
reduce(sum,list_1)
[out]>> 100
Now I will do same operation using anonymous function(lambda) method
# Method II
from functools import reduce
list_1=[10,15,25,10,40]
reduce(lambda a,b :a+b,list_1)
[out]>>100
Now I will create my own function to do reduce operation without taking the help of inbuilt
reduce()
function in python.
def myreduce(add,list_1):
return a
def add(a,b):
return a+b
list_1=[10,15,25,40,10]
a=list_1[0]
for i in range(1,len(list_1)):
b=list_1[i]
a=add(a,b)
print(myreduce(add,list_1))[out]>> 100
2. Creating
myfilter()
function
filter() function is used to eliminate the obsolete value eg:- I want to take only even number from the given list,then it will take only even number values as output and eliminate rest of numbers. It gives result iff the given result return true .
filter(func,iter_data)
here filter operation will be done on “func” function and “iter_data” is implying the iterable data values used to return result of output.
coding implementation using inbuilt filter()
function in python.
def is_even(a):
if a%2==0:
return True
list_1=[2,3,4,5,6,7,8,9,12345,5678,890,1234,567]
list(filter(is_even,list_1))[out]>> [2, 4, 6, 8, 5678, 890, 1234]
Now I will create my own function to do filter operation without taking the help of inbuilt
filter()
function in python.
def myfilter(is_even,list_2):
return is_even(a)
list_2=[2,3,4,5,6,7,8,9,10]
list_3=[]
def is_even(a):
for i in list_2:
if i%2==0:
list_3.append(i)
print(list_3)
myfilter(is_even,list_2)[out]>> [2, 4, 6, 8, 10]