Python 如何遍历队列?
我有这段代码,它将使用BFS搜索树中的叶节点Python 如何遍历队列?,python,queue,Python,Queue,我有这段代码,它将使用BFS搜索树中的叶节点 import queue def BFS(lst,que): jst=[] for x in range(len(lst)): if 2*x+1<=len(lst)-1 and 2*x+2<=len(lst)-1: que.put(lst[2*x+1]) que.put(lst[2*x+2]) for y in iter(que.get(),N
import queue
def BFS(lst,que):
jst=[]
for x in range(len(lst)):
if 2*x+1<=len(lst)-1 and 2*x+2<=len(lst)-1:
que.put(lst[2*x+1])
que.put(lst[2*x+2])
for y in iter(que.get(),None):
if y in lst:
if 2*(lst.index(y))<=len(lst)-1 and 2*(lst.index(y))+2<=len(lst)-1:
que.get()
return y
lst=[]
y=[]
x=int(input('Enter how many nodes:'))
if x%2==0:
print("not the correct no of nodes")
else:
for i in range(x):
lst.append((input("Enter the nodes: ")))
que=queue.Queue(maxsize=10)
y.append(BFS(lst,que))
print(y)
导入队列
def BFS(lst,que):
jst=[]
对于范围内的x(len(lst)):
如果2*x+1即使不使用iter()
,也没关系。函数queue.get()
用于从队列中取出下一个元素。因此,您的代码可能不使用iter()
导入队列
def BFS(lst,que):
jst=[]
对于范围内的x(len(lst)):
如果2*x+1即使不使用iter()
,也没关系。函数queue.get()
用于从队列中取出下一个元素。因此,您的代码可能不使用iter()
导入队列
def BFS(lst,que):
jst=[]
对于范围内的x(len(lst)):
如果2*x+1que.get()。一个元素是不可编辑的。尝试iter(que.get,None)
;您可以选择队列前面的任何元素。还有,为什么要用BFS来寻找树叶呢?DFS要简单得多。我在其他帖子中看到这种方法是有效的。链接到该帖子可能有助于理解您的想法。que.get()
从队列中获取一个元素,因此iter(que.get(),None)
正在尝试迭代单个元素。一个元素是不可编辑的。尝试iter(que.get,None)
;您可以选择队列前面的任何元素。还有,为什么要用BFS来寻找树叶呢?DFS要简单得多。我在其他帖子中看到这种方法是有效的。链接到那篇文章可能有助于理解你的想法。
import queue
def BFS(lst,que):
jst=[]
for x in range(len(lst)):
if 2*x+1<=len(lst)-1 and 2*x+2<=len(lst)-1:
que.put(lst[2*x+1])
que.put(lst[2*x+2])
for y in que.get():
if y in lst:
if 2*(lst.index(y))<=len(lst)-1 and 2*(lst.index(y))+2<=len(lst)-1:
que.get()
return y
lst=[]
y=[]
x=int(input('Enter how many nodes:'))
if x%2==0:
print("not the correct no of nodes")
else:
for i in range(x):
lst.append((input("Enter the nodes: ")))
que=queue.Queue(maxsize=10)
# also do not this change!
y = y.append(BFS(lst,que))
print(y)