trying to find all the path in a graph using DFS recursive in Python

后端 未结 2 586
耶瑟儿~
耶瑟儿~ 2021-01-16 04:34

I have found a solution that was posted some times ago and I have tried to apply it to my exercise but it doesn\'t work. I have a class graph that has nodes and edges and a

2条回答
  •  我在风中等你
    2021-01-16 05:20

    i've flattened JSON of nested dicts (depth was four)

    {'output':
        'lev1_key1': 'v11',
        'lev1_key2': {
           {'lev2_key1': 'v21',
            'lev2_key2': 'v22',
           }
     }
    

    with recursive call of

    paths = []
    _PATH_SEPARATOR = '/'
    def flatten(treeroot, path=''):
      path=path
      if isinstance(treeroot, dict):
        for k in treeroot.keys():
            s_path = path + _PATH_SEPARATOR + str(k)
            flatten(treeroot[k], path=s_path)
      elif isinstance(treeroot, str):
         path = path + _PATH_SEPARATOR + treeroot
         paths.append(path)
      elif isinstance(treeroot, list):
        # if node has more than one child 
        for k in treeroot.keys():
            s_path = path + _PATH_SEPARATOR + str(k)
            flatten(k, path=s_path)
    

    result is

    {
     'output/lev1_key1': 'v11',
     'output/lev1_key2/lev2_key1': 'v21',
     'output/lev1_key2/lev2_key2': 'v22',
    }
    

提交回复
热议问题