I am learning about recursion in python currently but there is this one exercise that I simply cannot figure out in the following code I have two functions and using recursion i print all possible numbers from a given list, but for the life of me I cannot get all the possible numbers into a single list. Any tips on how to do this would really be appreciated.
def find_possible_strings(char_set, n):
k = len(char_set)
return possible_stringsRec(char_set, "", k, n)
def possible_stringsRec(char_set, prefix, k, n):
if n == 0:
print(prefix)
return
for i in range(k):
newPrefix = prefix char_set[i]
possible_stringsRec(char_set, newPrefix, k, n - 1)
char_set = ['a','b']
possible_strings = find_possible_strings(char_set, 2)
print(possible_strings)
Just to specify I am not simply looking for a solution but rather an actual explanation of how this could be done in python if anyone would be so kind.
I am just getting the result as follows:
aa
ab
ba
bb
None
and what I want is for all those values to be stored inside a single list so essentially:
['aa', 'ab', 'ba', 'bb']
CodePudding user response:
Add a results=[]
keyword argument to the possible_stringsRec
function, and instead of printing out the values within the function, append to the results
list:
def find_possible_strings(char_set, n):
k = len(char_set)
return possible_stringsRec(char_set, "", k, n)
def possible_stringsRec(char_set, prefix, k, n, results=[]):
if n == 0:
results.append(prefix)
return
for i in range(k):
newPrefix = prefix char_set[i]
possible_stringsRec(char_set, newPrefix, k, n - 1)
return results
char_set = ['a','b']
possible_strings = find_possible_strings(char_set, 2)
print(possible_strings)
Output:
['aa', 'ab', 'ba', 'bb']
The explanation is pretty straightforward: the results
list starts out as empty when the first function call happens, and whenever a value get appended to it, the value remains inside the list for the next function call.
This demonstrates why:
def func(lst=[]):
lst.append(1)
print(lst)
func()
func()
func()
Output:
[1]
[1, 1]
[1, 1, 1]