(已修改,作者没错)广度优先搜索--算法图解--书中部分"错误"解决记录

在<图解算法>的第六章 广度优先搜索中,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()

 

★看到后面,才发现"错怪"作者了,因为人家的最终版本如下:

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


 

你可能感兴趣的:(python)