Showing posts with label reduce in python. Show all posts
Showing posts with label reduce in python. Show all posts

Thursday, September 10, 2015

Reduce,Map and Filter examples in the most simplest way

Map:

def to_gram(K):
    return (K * 1000)

def to_kilogram(G):
    return G/1000
   
grams=[5000,6000,7000]
kilograms=[1,2,3]

G=map(to_gram,kilograms)
K=map(to_gram,grams)

print "Grams ""+ G
print "Kgs" + K

Filter:
def div_by_2(x):
    return x % 2 == 0

arr = [1, 2, 3, 4]
new_arr = filter(div_by_2, arr)
new_arr will contain [2, 4]

reduce:

def add_arr(x, y):
    return x + y

arr = [1, 2, 3]

sum = reduce(add_arr, arr)