In [1]:
# 2.4: Functions

In [2]:
# 2.4.1: Defining custom functions

In [3]:
# 2.4.1.1: Simple function
def hello_world():
    return 'hello world'

In [4]:
hello_world()


Out[4]:
'hello world'

In [5]:
# 2.4.1.2: Empty function
def nothing(x):
    pass

In [6]:
# 2.4.1.3: Emulating the VLOOKUP function in Excel without loops
def VLOOKUP(age, cutoffs, left):
    if age <= min(cutoffs):
        return min(cutoffs)
    elif age >= max(cutoffs):
        return max(cutoffs)
    else:
        greater_than_age = list(map(lambda x: age < x, cutoffs))
        first_index = greater_than_age.index(True)
        if left:
            first_index = first_index - 1
        return cutoffs[first_index]

In [7]:
cutoffs = [1, 3, 7]
inputs = list(range(-1, 20))
inputs = list(map(lambda x: x/2, inputs))
results = list(map(lambda x: VLOOKUP(x, cutoffs, True), inputs))
[(a, b) for a, b in zip(inputs, results)]


Out[7]:
[(-0.5, 1),
 (0.0, 1),
 (0.5, 1),
 (1.0, 1),
 (1.5, 1),
 (2.0, 1),
 (2.5, 1),
 (3.0, 3),
 (3.5, 3),
 (4.0, 3),
 (4.5, 3),
 (5.0, 3),
 (5.5, 3),
 (6.0, 3),
 (6.5, 3),
 (7.0, 7),
 (7.5, 7),
 (8.0, 7),
 (8.5, 7),
 (9.0, 7),
 (9.5, 7)]

In [8]:
# 2.4.2: Function performance

In [9]:
# 2.4.2.1: Measuring execution time using the time module

In [10]:
import time

In [11]:
def sleep_for(x):
    time.sleep(x)
    return 'done'

In [12]:
start = time.time()
sleep_for(5)
end = time.time()
elapsed = end - start
print(elapsed)


5.005537033081055