You are on page 1of 22

Algoritma dan

Pemrograman

map, filter and


reduce

Adi
adi4vista@gmail.com
map, filter, reduce ?
• These are three functions which facilitate a
functional approach to programming
• alternative to list comprehension
• imperative vs declarative
• paradigma procedural -> imperative
• paradigma functional -> declarative
map
• built-in function
• map applies a function to all items in an input
list.
• blueprint:
– map(function, iterable)
• function: required. the function to execute for each
item
• iterable: required. a sequence, collection or an iterable
object.
map
• data: a1, a2, a3, ..., an
• function: f
• map(f, data):
– return iterator over
f(a1), f(a2), f(a3), ...., f(an)
contoh kasus
• mencari nilai pangkat dua dari sekumpulan
bilangan
solusi-1 [imperative]
solusi-2 [declarative]
solusi-2B [declarative]
filter
• built-in function
• filter create a list of elements for which a
function returns true.
• blueprint:
– filter(function, iterable)
• function: required. a function to be run for each item in
iterable
• iterable: required. the iterable to be filtered
contoh kasus
• carilah semua bilangan genap dari
sekumpulan bilangan acak yang ada
solusi-1 [imperative]
solusi-2 [declarative]
solusi-2B [declarative]
reduce
• reduce is a usefull function for performing some
computation on a list and returning the result.
• it applies a rolling computation to sequential pairs of
value in a list.
• it return a single result
• in python3, reduce is not a built-in function
• moved to the ‘functools’ module
• GVR, say:
“use functools.reduce() if you really need it. however,
99% of the time an explicit for loop is more readable.”
reduce
• data: a1, a2, a3, ..., an
• function : f(x, y)
• reduce(f, data):
– step 1 : val1 = f(a1, a2)
– step 2 : val2 = f(val1, a3)
– step 3 : val3 = f(val2, a4)
– ....
– step n-1 : valn-1 = f(valn-2, an)
– return valn-1

• return f(f(f(f(a1,a2),a3),a4)...an)
contoh kasus
• mencari hasil perkalian dari 10 bilangan positif
pertama
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 ?
solusi-1 [imperative]
solusi-2 [declarative]
solusi-2B [declarative]

You might also like