from time import sleep
def refit(i, n, c=[]):
sleep(1)
print(c)
if i[:n] != '': refit(i[n:],n,c [i[:n]])
sleep(1)
print(c)
return c
Output when using arguments "Helloo" and 2:
[]
['He']
['He', 'll']
['He', 'll', 'oo']
['He', 'll', 'oo']
['He', 'll']
['He']
[]
[]
The Array ['He', 'll', 'oo'] should be printed and returned, but the code is undoing itself. What is happening? I am so confused.
CodePudding user response:
Did you mean to save the return value from recursive calls to refit()
?
def refit(i, n, c=[]):
if i[:n] != '':
c = refit(i[n:], n, c [i[:n]])
return c
c = refit('Helloo',2)
print(c)
Output as requested
CodePudding user response:
Within a given call to refit
, you're not changing c
, so c
has the same value in the second print()
that it does in the first print()
. All the recursive calls happen in between those two print
calls.
On the first call, c
is []
:
# i = 'Helloo', n = 2, c = []
print(c) # prints "[]"
if i[:n] != '':
refit(i[n:],n,c [i[:n]]) # prints a bunch of other stuff
print(c) # prints "[]"
return c # returns []
On the second call to refit
(indicated above by # prints a bunch of other stuff
) we do:
# i = 'lloo', n = 2, c = ['He']
print(c) # prints "['He']"
if i[:n] != '':
refit(i[n:],n,c [i[:n]]) # prints even more stuff
print(c) # prints "['He']"
return c # returns ["He"]
Our output so far looks like:
[]
['He']
(more stuff will go here)
['He']
[]
And on and on -- each new recursive call adds another pair of print
statements in the middle of the previous call. And each call returns its original value of c
, rather than the new value it got from the recursive call it just made to refit
.
If you want this function to return the result from the innermost call, then it simply needs to return the result of calling refit
:
def refit(i, n, c=[]):
return refit(i[n:], n, c [i[:n]]) if i[:n] else c
print(refit("Helloo", 2)) # ['He', 'll', 'oo']