Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering the definition of a function without an assignment

Tags:

python

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.

like image 763
user3223332 Avatar asked Nov 30 '22 18:11

user3223332


2 Answers

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.

like image 163
Jeff Mercado Avatar answered Dec 05 '22 12:12

Jeff Mercado


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
like image 24
Claudiu Avatar answered Dec 05 '22 11:12

Claudiu