Block B

Assorted Oddments

Functions are Objects A function name is just another variable name.


>>> def f(x): return x + 2
... 
>>> f(5)
7
>>> f = 14

Now you can't call f because it's an integer!

Mary had a little Λ A lambda is a function without a name. Here is the general form.


lambda (args): return_value

Here are two examples. Notice the first one has no arguments.

lambda : print("cows")
lambda x, y, z : x*x + y*y + z*z

Here is some action in the sheep pen.


>>> (lambda x: 3*x + 1)(5)
16
>>> (lambda : print("cows"))()
cows
>>> quack = lambda x, y: x + y
>>> quack(4,5)
9

enumerate This iterates through any iterable and it returns a tuple (n, item) where n starts numbering a 0 and goes up by 1 each time, and item is an item in the iterable.


>>> x = ["cat", "dog", "elephant"]
>>> for k, item in enumerate(x):
...     print(f"x[{k}] = {x[k]}")
... 
x[0] = cat
x[1] = dog
x[2] = elephant
>>> for k, item in enumerate(x, 50):
...     print(k, item)
... 
50 cat
51 dog
52 elephant
>>> for k in enumerate("caterwaul", 10):
...     print(k[0], k[1])
... 
10 c
11 a
12 t
13 e
14 r
15 w
16 a
17 u
18 l
>>> for k, item in enumerate("caterwaul", 10):
...     print(k, item)
... 
10 c
11 a
12 t
13 e
14 r
15 w
16 a
17 u
18 l
>>> 
>>> 

def build_row(x, f):
    return f"<tr><td>{x}</td><td>{f(x)}</td></tr>"
def make_table(values, f):
    out = "<table>\n"
    out += "<tr><th>x</th><th>f(x)</th></tr>\n"
    for item in values:
        out += build_row(item, f) + "\n"
    out += "</table>\n"
    return out

values = [4,6,7,2,88,1, -4]
print(make_table(values, lambda x:x**3))

Here we test build_row

python table_of_values.py 
<tr><td>5</td><td>125</td></tr>

Here is the program we built.


def build_row(x, f):
    return f"<tr><td>{x}</td><td>{f(x)}</td></tr>"
def make_table(values, f):
    out = "<table>\n"
    out += "<tr><th>x</th><th>f(x)</th></tr>\n"
    for item in values:
        out += build_row(item, f) + "\n"
    out += "</table>\n"
    return out

values = [4,6,7,2,88,1, -4]
print(make_table(values, lambda x:x**3))
python table_of_values.py 
<table>
<tr><th>x</th><th>f(x)</th></tr>
<tr><td>4</td><td>64</td></tr>
<tr><td>6</td><td>216</td></tr>
<tr><td>7</td><td>343</td></tr>
<tr><td>2</td><td>8</td></tr>
<tr><td>88</td><td>681472</td></tr>
<tr><td>1</td><td>1</td></tr>
<tr><td>-4</td><td>-64</td></tr>
</table>