code: def _random_cycle(adj, random_state):
      
  
      # step through idx values in adj to pick a random one, random.choice does not work on dicts
      n = random_state.randint(len(adj))
      for idx, v in enumerate(adj):
          if idx == n:
              break
      start = v
  
      walk = [start]
      visited = {start: 0}
  
      while True:
          if len(walk) > 1:
              # as long as we don't step back one we won't have any repeated edges
              previous = walk[-2]
              neighbors = [u for u in adj[walk[-1]] if u != previous]
          else:
              neighbors = list(adj[walk[-1]])
  
          if not neighbors:
              # we've walked into a dead end
              return None
  
          # get a random neighbor
          u = random_state.choice(neighbors)
          if u in visited:
              # if we've seen this neighbour, then we have a cycle starting from it
              return walk[visited[u]:]
          else:
              # add to walk and keep moving
              walk.append(u)
              visited[u] = len(visited)
docs: Find a cycle using a random graph walk.