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]:
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]:
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)