[Python] Graph as dictionary of sets, how to iterate through neighbors (values in each set)

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to solve Leetcode problem 207. Course Schedule: https://leetcode.com/problems/course-schedule/description/

    For this, I implemented a Graph as a dictionary of sets (sort of an adjacency list).

    However my code throws

    TypeError: unhashable type: 'set'


    when I try to iterate through a node's neighbors on line

    for i in reverseGraph[cur]:


    class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
    # build adj list graph where a points to b
    graph = {}
    reverseGraph = {}
    for i in range(0, numCourses):
    graph = set()
    reverseGraph = set()
    for idx, prereq in enumerate(prerequisites):
    graph[prereq[0]].add(prereq[1])
    reverseGraph[prereq[1]].add(prereq[0])

    print("graph: ", graph)
    print("reverseGraph: ", reverseGraph)

    # see if we can take all courses in graph
    toRemoveStack = []
    for i in range(0, numCourses):
    if len(graph) == 0:
    toRemoveStack.append(i)
    print("toRemoveStack: ", toRemoveStack)
    while len(toRemoveStack) > 0:
    cur = toRemoveStack.pop()
    for i in reverseGraph[cur]:
    graph.remove(cur)
    if len(graph) == 0:
    toRemoveStack.append(graph)
    del graph[cur]

    return len(graph) == 0


    How does one correctly iterate though the neighbors? And yes I know there are other solutions on Leetcode using different algorithms. I just want to figure out if this representation of a Graph in Python is good or if it will bite me in the ass in interviews.

    Continue reading...

Compartilhe esta Página