Assignment on Programming Techniques for Big Data

Yoshi van den Akker and Georgios Gousios

Functional programming is the basis of most modern Big Data processing systems. Before going forward to the course, it is important to master data processing techniques using a functional programming style. In this assignment, your task is to train yourselves in thinking in a functional way when processing data.

Many of the the tasks below are easy, but some are not and require many iterations (and extensive testing!) to get right. For some of them, you can find ready-made solutions on the internet. Even though it may be tempting, we advise you against copying and pasting them here, as you will regret it later on in the course. Wax on, wax off!

This assignment has a total of 115 points. Your grade is calculated with min(points/11, 10), i.e. you need 110 points for a 10.

A few notes:

  • For each function you define, you also need to define at least one working example.
  • Do not change the given function signatures, otherwise automated tests will fail.
  • The tests will run every cell. Make sure no errors occur by testing this via Cell -> Run All.
  • Use functional programming for every question (besides the first section).
  • This assignment requires you to use Python 3.

Foundations of functional programming

In this part you will implement core functions that are vital to functional programming.

T (5pts): Implement map using iteration for lists/arrays

In [ ]:
def map(func, xs):
    res = []
    for x in xs:
        res.append(func(x))
    return res

map(lambda x: x*2, range(7))

T (5pts): Implement filter using iteration for lists/arrays

In [ ]:
def filter(func, xs):
    res = []
    for x in xs:
        if func(x):
            res.append(x)
    return res

filter(lambda x: x % 2 == 0, range(7))

T (5pts): Implement reduceR using iteration for lists/arrays

In [ ]:
def reduceR(func, xs, init):
    acc = init
    for x in xs[::-1]:
        acc = func(x, acc)
    return acc

reduceR(lambda x, y: x-y, range(7), 0)

T (5pts): Implement a function flatten(xs: [[A]]): [A] that converts a list of lists into a list formed by the elements of these lists. For example:

>>> a = [[1,2],[2,3],[3,[4]]]
>>> flatten(a)
[1,2,2,3,3,[4]]
In [ ]:
def flatten(xss):
    res = []
    for xs in xss:
        for x in xs:
            res.append(x)
    return res


flatten([[1,2,3],[4,5], [7,[8,9]]])

More basic functions

In every implementation from now (also in next steps)on you should reuse at least one of your answers to an earlier question.

T (5pts): Implement reduceL by reusing reduceR

In [ ]:
def reduceL(func, xs, init):
    return reduceR(lambda x,y: func(y,x), xs[::-1], init)

reduceL(lambda x, y: x-y, range(7), 0)

T (10pts): Implement group_by by reusing reduceL.

In [ ]:
def group_by(classifier, xs):
    def group_function(classifier, res, x):
        k = classifier(x)
        if k in res.keys():
            res[k].append(x)
        else:
            res[k] = [x]
        return res
    return reduceL(lambda x,y: group_function(classifier, x, y), xs, dict())
        
group_by(lambda x: "even" if x % 2 == 0 else "odd", range(10))

Simple data processing

T (5pts): Implement distinct using reduceL.

In [ ]:
def distinct(xs):
    return reduceL(lambda ys, y: ys if y in ys else ys + [y], xs, [])

a = [1,2,3,1,2,3,4,5,6,5,4,3,2,1]
distinct(a)

T (5pts): Implement flatmap.

In [ ]:
def flatmap(func, xs):
    return flatten(map(func, xs))

flatmap(lambda x: list(range(x)), range(5))

T (5pts): Implement max(xs: [Integer]): Integer that finds the largest value in xs. You can assume the list is non-empty.

In [ ]:
def max(xs):
    return reduceL(lambda x, y: x if x > y else y, xs, xs[0])

max([1,59,42,27,38])

Higher-order functions

T (10pts): Implement a function called drop_while(f: A -> Boolean, xs: [A]) : [A] that drops the longest prefix of elements from xs that satisfy f.

>>> a = [1,2,3,4,3,2,1]
>>> dropWhile(lambda x: x <= 3, a)
[4,3,2,1]
In [ ]:
def drop_while(func, xs):
    return reduceL(lambda x,y: x if func(y) and not x else x+[y], xs, [])

drop_while(lambda x: x <= 3, [1,2,1,3,5,3,1,4,1,5,6])

T (10pts): Implement a function zip(xs: [A], ys: [B]): List[(A,B)] that returns a list formed from this list and another list by combining the corresponding elements in pairs. If one of the two lists is longer than the other, its remaining elements are ignored.

>>> a = [1,2,3,4]
>>> b = [a,b,c,d,e]
>>> zip(a,b)
[(1, 'a'), (2, 'b'), (3, 'c'), (4,'d')]
In [ ]:
def zip(xs, ys):
    return reduceL(lambda x,y: x + [(xs[y], ys[y])], range(0, min(len(xs), len(ys))), [])
    
a = [2,3,4]
b = ['a','b','c','d']
zip(a,b)

T (10pts): Implement a function scanL(f: (acc: B, x: A) -> B, xs: [A], init: B) -> [B] that works like reduceL but instead of producing one final result, it also returns all the intermediate results.

>>> a = [2,3,4]
>>> scanL(a, 0, lambda x, y: x + y)
[0, 2, 5, 9]
In [ ]:
def scanL(func, xs, init):
    def helper(x , y):
        x.append(func(x[-1], y))
        return x
    return reduceL(helper, xs, [init])
    
scanL(lambda x, y: x + y, [2,3,4], 0)

Real life application

In the following questions you will solve realistic problems with the techniques you learned in this assignment. You will be working with data of San Francisco Library patrons. You can find the data file here. Below you can find what each field means.

  • Id: Id of patron
  • Patron Type Definition: Description of patron (adult, teen, child, senior, etc.).
  • Total Checkouts: Total number of items the patron has checked out from the library since the record was created.
  • Total Renewals: Total number of times the patron has renewed checked-out items.
  • Age Range: Age ranges: 0 to 9 years, 10 to 19 years, 20 to 24 years, 25 to 34 years, 35 to 44 years, 45 to 54 years, 55 to 59 years, 60 to 64 years 65 to 74 years, 75 years and over. Some blank.
  • Home Library Definition: Description of the branch library where the patron was originally registered.
  • Circulation Active Month: Month the patron last checked out library materials, or last logged into the library’s subscription databases from a computer outside the library.
  • Circulation Active Year: Year the patron last checked out library materials, or last logged into the library’s subscription databases from a computer outside the library.
  • Notice Preference Definition: Description of the patron’s preferred method of receiving library notices.
  • Provided Email Address: Indicates whether the patron provided an email address.
  • Year Patron Registered: Year patron registered with library system. No dates prior to 2003 due to system migration.
  • Outside of County: If a patron's home address is not in San Francisco, then flagged as true, otherwise false.
  • Supervisor District: Based on patron address: San Francisco Supervisor District. Note: This is an automated field, please note that if "Outside of County" is true, then there will be no supervisor district. Also, if the input address was not well-formed, the supervisor district will be blank.

Solve the following questions using functions you implemented earlier. The code for reading the file is already given. Hint: for testing purposes it could be beneficial to only use a small part of the dataset.

In [ ]:
# This snippet imports the csv file to a list of dicts

import csv
file = 'library.csv' # Change this filepath to the location of your file if necessary
patrons = []
try: 
    with open(file) as fh:
        rd = csv.DictReader(fh, delimiter=',') 
        for row in rd:
            patrons.append(row)
except FileNotFoundError as e:
    print(e)

T (10pts) Some patrons have indicated that they want to receive notices via email, but have not provided their email address. Implement a function that outputs a list of the IDs of these patrons.

In [ ]:
def missing_email(xs):
    return map(lambda x: x["Id"], filter(lambda x: x["Provided Email Address"] == "false" and x["Notice Preference Definition"] == "email", xs))

missing_email(patrons)

T (10pts) Implement a function that outputs the total amount of checkouts from members originally registered at a given location.

>>> checkouts(patrons, "Noe Valley/Sally Brunn")
1355624
In [ ]:
def checkouts(xs, location):
    return reduceL(lambda x, y: x + int(y), map(lambda x: x["Total Checkouts"], filter(lambda x: x["Home Library Definition"] == location, xs)), 0)

checkouts(patrons, "Mission")

T (15pts) Implement a function that lists the number of renewals per location in a tuple. Example output for part of the dataset:

>>> number_renewals(patrons)

[('Presidio', 431988),
 ('Mission', 1218976)]
In [ ]:
def number_renewals(xs):
    grouped = group_by(lambda x: x["Home Library Definition"], xs)
    return map(lambda x: (x, reduceL(lambda x, y: x + int(y["Total Renewals"]), grouped[x], 0)), grouped)
    
number_renewals(patrons)