Develop myFilter Function¶
Develop a function by name myFilter which takes a collection and a function as arguments. Function should do the following:
- Iterate through elements
- Apply the condition using the argument passed. We might pass named function or lambda function.
- Return the collection with all the elements satisfying the condition.
{note}
This is how the original function look like.
In [1]:
def get_customer_orders(orders, customer_id):
orders_filtered = []
for order in orders:
if int(order.split(',')[2]) == customer_id:
orders_filtered.append(order)
return orders_filtered
In [2]:
orders_file = open('/data/retail_db/orders/part-00000')
In [3]:
orders = orders_file.read().splitlines()
In [4]:
orders[:10]
Out[4]:
['1,2013-07-25 00:00:00.0,11599,CLOSED', '2,2013-07-25 00:00:00.0,256,PENDING_PAYMENT', '3,2013-07-25 00:00:00.0,12111,COMPLETE', '4,2013-07-25 00:00:00.0,8827,CLOSED', '5,2013-07-25 00:00:00.0,11318,COMPLETE', '6,2013-07-25 00:00:00.0,7130,COMPLETE', '7,2013-07-25 00:00:00.0,4530,COMPLETE', '8,2013-07-25 00:00:00.0,2911,PROCESSING', '9,2013-07-25 00:00:00.0,5657,PENDING_PAYMENT', '10,2013-07-25 00:00:00.0,5648,PENDING_PAYMENT']
In [5]:
get_customer_orders(orders, 11599)
Out[5]:
['1,2013-07-25 00:00:00.0,11599,CLOSED', '11397,2013-10-03 00:00:00.0,11599,COMPLETE', '23908,2013-12-20 00:00:00.0,11599,COMPLETE', '53545,2014-06-27 00:00:00.0,11599,PENDING', '59911,2013-10-17 00:00:00.0,11599,PROCESSING']
{note}
This is the example of implementation of generic libraries such as `filter`, `map`, `reduce` etc.
In [6]:
def myFilter(c, f):
c_f = []
for e in c:
if f(e):
c_f.append(e)
return c_f