1. 程式人生 > >廣度優先搜尋--演算法圖解--書中部分"錯誤"解決記錄

廣度優先搜尋--演算法圖解--書中部分"錯誤"解決記錄

在<圖解演算法>的第六章 廣度優先搜尋中,6.5進行演算法實現時,報如下錯誤:

UnboundLocalError: local variable 'search_queue' referenced before assignment
 

原始碼(書本是python2.x程式碼,轉換成python3.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在python2.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()