Recursive Nested Function
An interesting problem for your Python interview interviewer:
Write a function ‘funci’ that will return an argument integer (argument integer defaults to 0) incremented by 1.
Add an optional argument that will take an integer and return a function that will increment by 1 plus given argument value.
A new function should have the same signature and demonstrate accumulating increment behaviour.
Example behaviour:
f = funci
assert f() == 1, "f()"
assert f(1) == 2, "f(1)"
f1 = funci(y=1)
assert f1(0) == 2, "f1(1_0)"
assert f1(1) == 3, "f1(1_1)"
f2 = f1(y=2)
assert f2(0) == 4, "f2(2_1_0)"
assert f2(1) == 5, "f2(2_1_1)"
print("F3")
f3 = f2(y=-3)
assert f3() == 1, "f-3_2_1_"
assert f3(1) == 2, "f3(-3_2_1_1)"
The solution is below, so I will add a bit more space for those who might want to tackle it
Although it looks easy at the first glance, the problem appears when you try to implement the “keep signature” condition in the return lambda.
This problem cost me several hours. It also cost ChatGPT several hours for no good too. Then it took several hours of some bypassing victims
The final solution I’ve managed to come with may seem cheating. Yet, it allowed me to move on with my code
def funci(x=0, xacc=0, y=None):
if y is None:
return x+xacc+1
return lambda x=0, xacc=xacc+x+y, y=None: funci(x=x, xacc=xacc, y=y)
I would not suggest showing this solution to the interviewer though