from collections import deque
def person_is_mangoSeller(name):
return name[-1] == 'm'
graph = {}
graph["you"] = ["Alice"]
graph["Alice"] = ["Cindy","you"]
graph["Cindy"] = ["Tom"]
def search(name):
search_deque = deque()
search_deque += graph[name]#graph变为graph[name]
searched = []
while search_deque:
person = search_deque.popleft()#popleft() takes no arguments
if person not in searched:
if person_is_mangoSeller(person):
print name + " " + "is a mango seller"
return True
else:
search_deque += graph[person]
searched.append(person)
return False
search("you")
结果显示“you is a mango seller”。本来一直不懂:我不是已经创造了一个数组放检查过的人了吗??怎么还会出现you呢?
后来经过不断的调试才发现:search("you")时,检查的其实是Alice,跟“you”是没有关系的。
但是还是不对啊!问题不在这里。
又调试一遍,原来,是19行中name的问题,因为在整个过程中,我传入的name是永远不变的,都是“you”,变的是被推出的person。所以,正确的代码应该是:
#查找芒果商
from collections import deque
def person_is_mangoSeller(name):
return name[-1] == 'm'
graph = {}
graph["you"] = ["Alice"]
graph["Alice"] = ["Cindy","you"]
graph["Cindy"] = ["Tom"]
def search(name):
search_deque = deque()
search_deque += graph[name]#graph变为graph[name]
searched = []
while search_deque:
person = search_deque.popleft()#popleft() takes no arguments
if person not in searched:
if person_is_mangoSeller(person):
print person + " " + "is a mango seller"
return True
else:
search_deque += graph[person]
searched.append(person)
return False
search("you")
好吧,虽然不是什么含金量高的错误,但解决了还是很有意义。