문제

나는 내 맛을 너무 많이 사용하고있다 (검색의 모든 솔루션 분기).주어진 광장에서 Boggle 단어를 찾는 코드입니다.단어가 이웃 인 이웃 인 이웃 사람이있는 이웃 사람 만 포함하는 단어가 미리 선택되어 있지 않으면 버그가있었습니다.

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
.

어떤 대답이 발견 된 후에 멈추는 발전기를 만드는 것이 더 나은 대안이 있습니까?

솔루션을 기반으로 한

마침내 나에게 가져 왔고 반환 된 순서는 가치가 없어지지 않아도 되돌아가는 것이 반복됩니다.그래서 나는 워드 _PATH 코드를 변경하여 반품을 사용하고 일반적으로 표현식을 정리합니다.함수가 없음 또는 false를 제공하는 대신 (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])
.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top