Change function definition without assignment

I was given this task:

Write a one-line expression that converts the function f (x) to f (x) +1. Hint: Consider how a local frame binding for a stored value of f can be created without 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 uses the assignment f=f. How could I do this without an appointment?

My teacher told me that Python has a function similar to a function letin Scheme, but I'm not sure that this function wants us to use it because it did not specify the name of the function.

+4
source share
2 answers

This will work, but it could be a hoax:

>>> 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
+9

, , , :

def f(x, f=f): return f(x) + 1

" () ", , , .

+10

Source: https://habr.com/ru/post/1568034/


All Articles