在第一个答案中停止发电机,使用返回
-
28-09-2020 - |
题
我对我的品味太多了模式(在搜索的每个可能的解决方案分支后)。这是在给定广场上找到摇晃单词的代码。如果没有预选的单词,它只包含那些字母对是邻居的那些,它有一个错误,我现在通过改变comprarrision而不是pos来修复的那些。
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
.
是否有更好的替代方案来制作在发现任何答案后停止的发电机?
解决方案,基于为什么不使用返回
最后它得到了我,返回的序列是迭代器,无论它返回不产生价值。所以我更改了我的Word_Path代码以使用返回并通常清理表达式。而不是没有给出函数返回(false,)。然后我没有问题没有任何不被陈述。
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,)
. 解决方案
为什么你只想在第一个答案的地方制作一个发电机?只需搜索答案并返回第一个而不是产生它。
其他提示
return iter([anwser])
. 不隶属于 StackOverflow