简体   繁体   中英

Find cycle in directed graph, return statement

I coded up a WORKING solution to find a cycle in a DIRECTED graph, however I would like to know the reason to include a return False statement after removing a key from the recursion stack.


class vertex:

  def __init__(self, key):

    self.neighbours = {}
    self.key = key

  def add(self, key, edge):
    self.neighbours[key] = edge

class graph:

  def __init__(self):

    self.root = {}
    self.nbnodes = 0

  def addnode(self, key1, key2, edge=0):
    if key1 not in self.root:
      self.root[key1] = vertex(key1)
      self.nbnodes += 1
    if key2 not in self.root:
      self.root[key2] = vertex(key2)
      self.nbnodes += 1

    self.root[key1].add(key2, edge)

  def dfs(self):

    visited = set()
    recstack = []

    for key in self.root:
      if key not in visited:
        if self._dfs(key, visited, recstack):
          print('cycle')
        else:
          print('No cycle')


  def _dfs(self, key, visited, recstack):

    visited.add(key)
    recstack.append(key)
    for neighbour in self.root[key].neighbours:
      if neighbour not in visited:
        if self._dfs(neighbour, visited, recstack):
          return True
      elif neighbour in recstack:
        return True
    recstack.remove(key)  
    #return False



if __name__ == '__main__':
  a = graph()
  a.addnode(0,1)
  a.addnode(0,2)
  a.addnode(1,3)
  a.addnode(1,4)
  a.addnode(2,4)
  a.addnode(4,5)
  a.dfs()

The above is my final solution code, I commented out the return False statement, I would like to know why to include it.

Thank you

If you ask for the reason, the obvious answer is readability.

Without explicit return False your are implicitly returning None , which, so it happens for fragment if self._dfs(neighbour, visited, recstack): works the same as the commented return False . Still I was unclear about the intent and would assume you forgot to return it (or wanted to point the reader there is no status of function in the case).

Citing documentation :

None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

Your value is not absent, it is perfectly defined for your function. Other than following good practices, it won't change anything in your code.

BTW. Names of classes are usually capitalized and CamelCase, while functions use snake_case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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