I am using too much to my taste the pattern (after every possible solution branch of the search). This is the code to find boggle words in given square. It had a bug if the words are not preselected to include only those whose letter pairs are neighbours, which I fixed now by changing comparrision not pos to pos is None.
def word_path(word,used=[],pos=None):
if not word:
yield False
return
else:
correct_neighbour = [neigh for p,neigh in neighbour_set
if (not pos or pos==p) and (neigh not in used) and boggle[neigh]==word[0] ]
for i in correct_neighbour:
used_copy=used[:]+[i]
if boggle[i]==word:
yield used_copy
return
else:
for solution in word_path(word[1:],used_copy,pos=i) or (False,):
if solution:
yield solution
return
Is there any better alternative to make generator which stops after any answer was found?
Solution based on why not use return
Finally it got me and returned sequence is iterator no matter that it was returned not yielded value. so I changed my word_path code to use return and cleaned up the expressions generally. Instead of giving None or False the function returns (False,). Then I have not problem with None not accepted for for statement.
def word_path(word,used=[],pos=None):
if word:
correct_neighbour = [neigh
for p,neigh in neighbour_set
if ((pos is None or pos==p) and
(neigh not in used) and
boggle[neigh]==word[0]
)
]
for i in correct_neighbour:
used_copy=used[:]+[i]
if len(word)==1:
if boggle[i]==word:
return (used_copy,)
else:
for solution in word_path(word[1:],used_copy,pos=i):
if solution:
return (solution,)
return (False,)