简体   繁体   English

Python:使用递减集合中的next和iter检测循环

[英]Python: Detect cycle using next and iter in a diminishing set

I was following Tushar Roy's video on detecting cycles in directed graphs.我正在关注 Tushar Roy 关于检测有向图中循环的视频 I understand the use of the white, gray and black sets to detect the cycle but the main thing that I don't understand is how as we check for the length of the white set, next(iter(white)) would know where to go next since the set size has changed.我理解使用白色、灰色和黑色集来检测循环,但我不明白的主要事情是当我们检查white集的长度时, next(iter(white))会知道在哪里由于设置大小已更改,因此请下一步。 The documentation says that iter gives you an iterator object and next would retrieve the next item.文档说iter为您提供了一个迭代器对象, next将检索下一个项目。 Is the main point that the iterator is evaluated differently each time?迭代器每次被评估的要点是不同的吗?

You can find the code here or here .您可以在此处此处找到代码。

def has_cycle(graph):
    white = set()
    gray = set()
    black = set()

    for vertex in graph.all_vertex.values():
        white.add(vertex)

    while len(white) > 0:
        current = next(iter(white))       
        if dfs(current, white, gray, black) == True:
            return True

    return False        

def dfs(current, white, gray, black):
    move_vertex(current, white, gray)
    for neighbor in current.adjacent_vertices:
        if neighbor in black:
            continue
        if neighbor in gray:
            return True
        if dfs(neighbor, white, gray, black) == True:
            return True

    move_vertex(current, gray, black)
    return False

def move_vertex(vertex, source_set, destination_set):
    source_set.remove(vertex)
    destination_set.add(vertex)

next(iter(white)) just returns an element of the set white . next(iter(white))只返回集合white一个元素。 A set is not ordered so there is no guarantee as to which element is picked.集合不是有序的,因此不能保证选择哪个元素。 You are right to think the iterator is evaluated for each iteration of the loop.您认为迭代器会针对循环的每次迭代进行评估是正确的。

The fact that the set changes as the loop progresses forbids the use of a for loop.集合随着循环的进行而改变的事实禁止使用for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM