I have a simple recursive function that provides a depth first search of each possible combination of a list of options:
def twoCharacters_dfs(options, used):
for i in range(len(options)):
used.append(options.pop(0))
print("used=", used)
twoCharacters_dfs(options, used)
if len(used) == 0:
return
options.append(used.pop())
twoCharacters_dfs(['q', 'w', 'e', 'r'], [])
The ouput (shortened due to length) looks as follows:
used= ['q']
used= ['q', 'w']
used= ['q', 'w', 'e']
used= ['q', 'w', 'e', 'r']
used= ['q', 'w', 'r']
used= ['q', 'w', 'r', 'e']
used= ['q', 'e']
used= ['q', 'e', 'r']
used= ['q', 'e', 'r', 'w']
used= ['q', 'e', 'w']
used= ['q', 'e', 'w', 'r']
....
used= ['w']
....
used= ['e']
....
used= ['r']
....
And that is all well and good and works how i want it. But I am interested in converting this from depth first to breadth first so the output looks more like:
used= ['q']
used= ['w']
used= ['e']
used= ['r']
used= ['q', 'w']
used= ['q', 'e']
used= ['q', 'r']
used= ['w', 'q']
used= ['w', 'e']
used= ['w', 'r']
....
I have been somewhat able (only a hard-coded fixed length list) to do it iteratively, but desire a recursive solution so it can work for any length of options. I am also purposely avoiding python libraries that provide the functionality i seek because i would like to understand how things work and build my own stuff as a learning exercise.
I feel like there is a simple solution, but i am having trouble conceptualizing the breadth first algorithm into my code.
UPDATE
Before attempting a recursive BFS solution i wanted to create an iterative BFS solution as it appears to be easier to implement. As it turns out, i am also having trouble doing that.
def twoCharacters_bfs_iterative(options, used):
for option in options:
print("using option = ", option)
for option1 in options:
list2 = options[:]
list2.remove(option1)
for option2 in list2:
print("using option = ", option1, option2)
for option1 in options:
list2 = options[:]
list2.remove(option1)
for option2 in list2:
list3 = list2[:]
list3.remove(option2)
for option3 in list3:
print("using option = ", option1, option2, option3)
This achieves my desired output (listed above), but only works for a set where i know the length. I want to expand it for a list of an arbitrary length, but am having trouble doing that. I imagine if I can get the iterative solution working, a recursive solution isn't far behind.