uwhpsc-2016 / homework1

Homework #1
1 stars 1 forks source link

Exercise 2: functions as arguments to other functions #48

Open gadamico opened 8 years ago

gadamico commented 8 years ago

I'm a little confused about the syntax for passing functions as arguments to other functions. There is talk on stackoverflow about 'lambda' and about using asterisks (like 'args' or '*kwargs'?), but I'm not sure if these are necessary.... In a Jupyter Notebook I tried defining new functions f and df and then calling my gradient functions with references to those new functions ... but this didn't seem to work. gradient_step kept returning a 'None' value (but the command was executed, so maybe the problem is in my code for gradient_step?).

alyfarahat commented 8 years ago

Update: added "lambda" to the example code.

did you try

f = lambda u : u**3 # for defining a cubic function
df = lambda u: 3*(u**2) # for defining the derivative
x0 = 1
gradient_descent_iteration(f, df, x0) # Run gradient descent algorithm

and did not work?

Try to take a look at unit tests as well.

cswiercz commented 8 years ago

In Python, functions are objects just like anything else. They can be passed to other functions. For example

def foo(x):
    return x**2

def bar(f,y):
    return 2*f(y)

print bar(foo, 3)  # prints 18 = (3**2) * 2

"lambda" functions are a tool for quickly (and clearly) writing a function in one line.

gadamico commented 8 years ago

Thanks. So you don't have to write "def f(x etc.)"?

quantheory commented 8 years ago

Exactly. I wouldn't recommend lambda for functions that are at all complex or frequently used, because you probably want to write those out clearly and document them. But they can be useful, for instance, if you are using a function that requests another function as input, as in cswiercz's example.

>>> square = lambda x: x*x
>>> square(4)
16

Or even more simply (not that you would ever have a reason to do this):

>>> (lambda x: x*x)(4)
16
gadamico commented 8 years ago

Thanks, Sean.

jdstead commented 8 years ago

In Chris's example, where is the function f defined?

quantheory commented 8 years ago

It's the argument to bar. So when bar(foo, 3) is called, foo is used as the function f, and 3 is used as the argument y.