Libraries and Modules in Python

Solutions

Add Doctrings

In [17]:
def add(a, b):
    """Calculates the element-wise sum of a and b, returning a list of the results"""
    c = []
    for x,y in zip(a,b):
        c.append(x+y)
    return c
In [18]:
help(add)
Help on function add in module __main__:
add(a, b)
    Calculates the element-wise sum of a and b, returning a list of the results
In [19]:
def subtract(a, b):
    """Calculates the element-wise ratio of a and b, returning a list of results. This function
       is badly named, as it DOES NOT return the element-wise difference of a and b!"""
    c = []
    for x,y in zip(a,b):
        c.append(x / y)
    return c
In [20]:
help(subtract)
Help on function subtract in module __main__:
subtract(a, b)
    Calculates the element-wise ratio of a and b, returning a list of results. This function
    is badly named, as it DOES NOT return the element-wise difference of a and b!
In [21]:
def capitalise(message):
    """Capitalises every word in message, returning the result"""
    words = message.split(" ")
    for i in range(0,len(words)):
        words[i] = "%s%s" % (words[i][0].upper(), words[i][1:])
    return " ".join(words)
In [22]:
help(capitalise)
Help on function capitalise in module __main__:
capitalise(message)
    Capitalises every word in message, returning the result
In [23]:
def surprise(x):
    """Prints 'Surprise!' if x is less than a random number between 0 and 1. Returns nothing"""
    import random
    if x < random.random():
        print("Surprise!")
In [24]:
help(surprise)
Help on function surprise in module __main__:
surprise(x)
    Prints 'Surprise!' if x is less than a random number between 0 and 1. Returns nothing

For this last function, try calling it via list_interface("ipynb").

In [25]:
def list_interface(x):
    """Returns a list of all files in the current directory that start with '0' and end with x"""
    import glob
    f = glob.glob("*.%s" % x)
    l = []
    for x in f:
        if x.startswith("0"):
            l.append(x)
    return l
In [26]:
help(list_interface)
Help on function list_interface in module __main__:
list_interface(x)
    Returns a list of all files in the current directory that start with '0' and end with x