I found a function on the web that generates all sub-multisets of a set and then returns them. But as i walked the code through to understand what it actually does, i really got stuck.
Here’s the code:
def build_substrings(string):
""" Returns all subsets that can be formed with letters in string. """
result = []
if len(string) == 1:
result.append(string)
else:
for substring in build_substrings(string[:-1]):
result.append(substring)
substring = substring + string[-1]
result.append(substring)
result.append(string[-1])
return result
Now, let’s say i call it with an arguement “ab”. The base case is ignored, so i get to the else block and call the function again, now the argument being “a”. I get to the base case and it appends “a” to result. now i return the result. the for loop is now ‘activated’. substring is assigned “a” and it is appended to the result list. Now, i have appended “a” two times to the list called ‘result’ . Somehow, in the output it is shown only once.
Thank you very much for your help.
No,
resultis a local variable, and the first time you append “a” to it, it’s the localresultofbuild_substrings("a")whereas the second time it’s the localresultofbuild_substrings("ab"). They are two different calls to your method so they don’t share theirresult.