User-Defined Functions, Continued
Let's briefly cover some more features of Python functions
One-Line Functions: 'lambda'
The
lambda
keyword is used to create simple functions on one line
Let's suppose we want to create a function
f
such that f(x) = x**3
One way to do this is as follows
def f(x):
return x**3
We can also achieve this using the
lambda
keywordf = lambda x: x**3
Here
lambda x: x**3
creates the function, and then f
is bound to itlambda
is often used to create anonymous functions (i.e., no name is bound)
For example, suppose we have a Python function
integrate()
as followsdef integrate(f, a, b):
# Compute the integral of f on [a, b] and return it
Now we want to integrate
f(x) = x**2 - x
on [0, 1]
Instead of first defining
f
, we can use the convenient syntaxintegrate(lambda x: x**2 - x, 0, 1)
The function is anonymous, since no name is bound to it
Keyword Arguments
In general, the order in which arguments are passed to functions is important
integrate(f, a, b)
is not the same asintegrate(a, f, b)
Can become difficult to remember the correct order when there are many arguments
In this case one possibility is to use keyword arguments
def g(word1="Charlie ", word2="don't ", word3="surf."):
print(word1 + word2 + word3)
The values supplied to the parameters are called defaults
>>> g() # Prints "Charlie don't surf"
>>> g(word3="swim") # Prints "Charlie don't swim"
The order we give the arguments doesn't matter any more
>>> g(word3="Beats", word2="Rockin ", word1="Block ")
Block Rockin Beats
If we don't wish to specify particular default value, convention is to use
None
For example, let's modify our
integrate()
function from abovedef integrate(function=None, start=None, stop=None):
# Code here
Now we can call the function as follows:
integrate(function=lambda x: x**2 - x, start=0, stop=1)
Recursive Function Calls
Not an easy topic, and not something that you will use every day
- Feel free to skip this topic for now
- But it is still useful: you need to learn it at some stage
Basically, a recursive function is a function that calls itself
For example, consider the problem of computing xt for some t when
Obviously the answer is 2t
And we can compute this with a loop
def x_loop(t):
x = 1
for i in range(t):
x = 2 * x
return x
Here's a recursive solution to the same problem
def x(t):
if t == 0:
return 1
else:
return 2 * x(t-1)
Each successive call uses it's own frame in the stack
- a frame is where the local variables of a given function call are held
- stack is memory used to process function calls
- a First In Last Out (FILO) queue
Problem:
The Fibonacci numbers are defined by
The first few numbers in the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Write a function to recursively compute the t-th Fibonacci number for any t
Solution:
def x(t):
if t == 0:
return 0
if t == 1:
return 1
else:
return x(t-1) + x(t-2)
0 comments:
Post a Comment