Reputation: 157
I was given the following question:
Write a function last_in(x) that returns the value of x used in the previous call. The first time that the function is called, it will return None.
I did something that somewhat works, but something is missing. Here's my attempt:
def last_in(x):
def inner():
return x
return inner()
And the output of
print(last_in(3),last_in(4),last_in(5), last_in("a"),last_in("12"))
is
3 4 5 a 12
But the expected needs to be
None 3 4 5 a
What do I miss?
Thank you!
Upvotes: 2
Views: 101
Reputation: 953
Functions are objects and can have attributes. You can, therefore, store the previous number as an attribute.
def last_in(x):
if hasattr(last_in, 'last_num'): curr_num = last_in.last_num
else: curr_num = None
last_in.last_num = x
return curr_num
print(last_in(2))
print(last_in(3))
print(last_in(4))
Output:
None
2
3
Upvotes: 1
Reputation: 7844
Another approach would be to use a Mutable Default Argument:
def last_in(x, prev=[None]):
prev.append(x)
return prev[-2]
print(last_in(3),last_in(4),last_in(5), last_in("a"),last_in("12"))
This will produce:
None 3 4 5 a
Upvotes: 2
Reputation: 6056
You are creating a function inner
and immediately calling it. So this:
def last_in(x):
def inner():
return x
return inner()
is roughly equivalent to this:
def last_in(x):
return x
What you can do is, define a variable and access it using global
keyword:
last_x = None
def last_in(x):
global last_x
return_value, last_x = last_x, x
return return_value
print(last_in(3), last_in(4), last_in(5), last_in("a"), last_in("12"))
None 3 4 5 a
Upvotes: 2
Reputation: 10590
You can create an attribute for your function to store previous values, e.g. last_in.prev_val
. This is somewhat similar to static variables in other languages. You just need to make sure you handle initializing the attribute appropriately. getattr
is useful as @Feodoran mentions.
def last_in(x):
return_val = getattr(last_in, 'prev_val', None)
last_in.prev_val = x
return return_val
print(last_in(3), last_in(4), last_in(5), last_in("a"), last_in("12"))
Ouptput:
None 3 4 5 a
Upvotes: 2
Reputation: 195478
You can do it without global variable:
def last_in(x, last = [None]):
v, last[0] = last[0], x
return v
print(last_in(3),last_in(4),last_in(5), last_in("a"),last_in("12"))
Prints:
None 3 4 5 a
Upvotes: 0
Reputation: 605
You can maintain a global list of inputs passed to the function.
valueList=[]
def last_in(x):
def inner():
valueList.append(x)
if(len(valueList)!=1):
return valueList[len(valueList)-2]
else:
return None
return inner()
print(last_in(3),last_in(4),last_in(5), last_in("a"),last_in("12"))
OUTPUT: None 3 4 5 a
Upvotes: 1