gpt4 book ai didi

python - 如何遍历队列?

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:58 25 4
gpt4 key购买 nike

我有这段代码,它将使用 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(),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)

它向我显示了一个错误:TypeError: iter(v, w): v must be callable,而我在其他帖子中看到此方法有效。还有其他方法可以遍历队列吗?

最佳答案

即使不使用iter()也没关系。函数queue.get() 的作用是从队列中取出下一个元素。因此,您的代码可以在不使用 iter() 的情况下工作。

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)

关于python - 如何遍历队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com