Trying to implement an algorithm using recursion in python. looks like something is missing which I am not able to debug.
My approach is to have two branches of recursion and passing an element at every recursion. details below:
## input pattern : "ab"
## output pattern : ["", "a", "b", "ab"]
# "ab" [ROOT]
# |
# -a +a
# | |
# -b +b -b +b
# => "" "b" "a" "ab"
my existing code is below: it is not working as expected.
def gen_subset(slist):
def helper(slist,i,temp,out):
if len(slist) == i:
out.append(temp)
return()
else:
helper(slist,i+1,temp,out)
temp.append(slist[i])
helper(slist,i+1,temp,out)
out = []
helper(slist,0,[],out)
return out
s = "ab"
print (gen_subset([c for c in s]))
this code produces the wrong result.
Output
[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]
am I missing anything here?
答案 0 :(得分:4)
Change temp.append(slist[i])
to temp = temp + [slist[i]]
.
This is happening because temp.append()
modifies the temp
variable in-place.
Instead we need to pass a copy of temp
to the next recursion call.