У меня есть эта функция python для DFS, почему она выдает ошибку?

#python #graph

#python #График

Вопрос:

 ##This function will return the edges for an undirected graph####
###Example: when edges = [[1,2],[3,2]]
### this will return 
{
    1: {'nbr': [2], 'id': 1, 'visited': False},
    2: {'nbr': [1, 3], 'id': 2, 'visited': False},
    3: {'nbr': [2], 'id': 3, 'visited': False}
}

def createEdges(edges):
    E = {}
    for y in edges:
        for x in edges:
            if x[0] not in E:
                E[x[0]] = {"id": x[0], "nbr": [x[1]], "visited": False}
            elif x[1] not in E:
                E[x[1]] = {"id": x[1], "nbr": [x[0]], "visited": False}
            elif x[0] in E and x[1] not in E[x[0]]['nbr']:
                E[x[0]]['nbr'].append(x[1])
            elif x[1] in E and x[0] not in E[x[1]]['nbr']:
                E[x[1]]['nbr'].append(x[0])
    return E

    ####A function to explore the a vertex of the graph with edges E

def explore(vertex, E):
    if vertex not in E:
        return
    E[vertex]['ccNum'] = cc
    E[vertex]['visited'] = True
    for x in E[vertex]['nbr']:
        if E[x]['visited'] == False:
            explore(x, E)
            ### this function will set the visited index to true for 
            ### all the connecting points of the vertex

            ###  A function for DFS

def DFS(E):
    cc = 1
    for x in E:
        if E[x]['visited'] == False:
            explore(x, E)
            cc  = 1
 

Все работало задолго до введения «cc», который отслеживает
общее количество подключаемых вложенных графиков

Теперь он выдает ошибку, которая:

Глобальное имя cc не определено

хотя cc определен, expose вызывается в DFS, в области видимости которой определен cc

Ответ №1:

Да, cc определяется в области видимости DFS , что не делает его видимым внутри explore . Вы могли бы определить ее как параметр для explore ;

 def explore(vertex, E, cc):
 

и передайте значение;

 . . .
explore(x, E, cc)
. . .
 

Ответ №2:

вам нужно определить «cc» как параметр explore или определить его как глобальную переменную.

  cc = 0
 def explore(vertex, E):
   global cc
   if vertex not in E:
      return
   E[vertex]['ccNum'] = cc
   E[vertex]['visited'] = True
   for x in E[vertex]['nbr']:
      if E[x]['visited'] == False:
           explore(x, E)
          ### this function will set the visited index to true for 
           ### all the connecting points of the vertex

          ###  A function for DFS

def DFS(E):
  cc = 1
  for x in E:
      if E[x]['visited'] == False:
        explore(x, E)
        cc  = 1