(修正済み、著者は間違いない)広さ優先検索--アルゴリズム図解--本の一部の「エラー」解決記録
2995 ワード
の第6章の広さ優先探索において、6.5がアルゴリズム実装を行う場合、以下のエラーを報告する.
UnboundLocalError: local variable 'search_queue' referenced before assignment
ソースコード(本はpython 2.xコード、python 3.xフォーマットに変換)は以下の通りです.
次のブロガーがまとめた第3条(markを先にして、それからゆっくり研究して、この兄貴に感謝します):
-------------------
◆グローバル変数エラー:UnboundLocalError:local variable'l'referenced before assignment
https://blog.csdn.net/my2010sam/article/details/17735159
3.内部関数が同じ名前のグローバル変数を変更する前に変数名(print sumなど)を呼び出すと、Unbound-LOcalErrorが起動します.
-------------------
一時的な解決策search_Queueはwhileループに格納されますが、次のようにエラーが表示されます.
SyntaxError: 'return' outside function
解決策はwhileサイクルを関数全体の下に置くことであり、問題はない.(returnは関数/メソッドの内部しか話せません)、完全なコードは以下の通りです.
★returnがpython 2にあることを知らなかった.xでの使用は関数/方法以外である必要はないか.
★後を見て、「錯怪」の作者を発見しました.人の最終バージョンは以下の通りです.
UnboundLocalError: local variable 'search_queue' referenced before assignment
ソースコード(本はpython 2.xコード、python 3.xフォーマットに変換)は以下の通りです.
from collections import deque
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph['thom'] = []
graph['jonny'] = []
search_queue = deque()
search_queue += graph['you']
while search_queue:
person = search_queue.popleft()
if person_is_seller(person):
print(person + ' is a mango seller!')
return True
else:
search_queue += graph[person]
return False
def person_is_seller(name):
return name[-1] == 'm'
次のブロガーがまとめた第3条(markを先にして、それからゆっくり研究して、この兄貴に感謝します):
-------------------
◆グローバル変数エラー:UnboundLocalError:local variable'l'referenced before assignment
https://blog.csdn.net/my2010sam/article/details/17735159
3.内部関数が同じ名前のグローバル変数を変更する前に変数名(print sumなど)を呼び出すと、Unbound-LOcalErrorが起動します.
-------------------
一時的な解決策search_Queueはwhileループに格納されますが、次のようにエラーが表示されます.
SyntaxError: 'return' outside function
解決策はwhileサイクルを関数全体の下に置くことであり、問題はない.(returnは関数/メソッドの内部しか話せません)、完全なコードは以下の通りです.
★returnがpython 2にあることを知らなかった.xでの使用は関数/方法以外である必要はないか.
from collections import deque
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph['thom'] = []
graph['jonny'] = []
def def_search_queue():
search_queue = deque()
search_queue += graph['you']
while search_queue:
person = search_queue.popleft()
if person_is_seller(person):
print(person + ' is a mango seller!')
return True
else:
search_queue += graph[person]
return False
def person_is_seller(name):
return name[-1] == 'm'
def_search_queue()
★後を見て、「錯怪」の作者を発見しました.人の最終バージョンは以下の通りです.
def search():
search_queue = deque()
search_queue += graph['you']
searched = []
#
while search_queue:
person = search_queue.popleft()
if person not in searched:
#
if person_is_seller(person):
print(person + " is a mango seller!")
return True
else:
search_queue += graph[person]
searched.append(person)
#
return False