I was given this task:
Write a one-line expression that transforms an f(x) function into f(x) +1. Hint: think about how a local frame binding for saved value of f, can be created without an assignment.
Example:
>>> f = lambda x: x*x >>> f(5) 25 >>> ---your one line expression--- >>> f(5) 26 >>> f, g = None, f >>> g(5) 26
I tried to do this:
k,f=f, lambda x: k(x)+1
And it works but it uses the assignment f=f
. How could I do this without an assignment?
My teacher told me that there is a function in Python similar to the let
function in Scheme, but I'm not sure what this function is that she wants us to use because she did not provide the name of the function.
This is not something that should be used in general, but I suppose you could do this:
def f(x, f=f): return f(x) + 1
And there's "no (explicit) assignments" since we're just defining a new function name which happens to be the same as the original.
This will work, but it may be cheating:
>>> f = lambda x: x*x
>>> f(5)
25
>>> globals().update({'f': (lambda g: lambda x: g(x)+1)(f)})
>>> f(5)
26
>>> f, g = None, f
>>> g(5)
26
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With