面试题(数据结构格式拍平)

  • 一道简单的面试题

描述: 将一个类似图的结构换一个格式输出

  • Input:

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    graph = {
    'data': {},
    'f1': {'data'},
    'f2': {'f1'},
    'f3': {'f2', 'f5'},
    'f5': {'f4'},
    'f4': {'data'},
    'model': {'f3'}
    }
  • Output:

  • 1
    [{'f3': [{'f2': [{'f1': 'data'}]}, {'f5': [{'f4': 'data'}]}]}]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def test(graph):
ret = {'model':[]}
iter_node = graph['model']
def digui(node):
ret = []
for k in node:
if graph[k] == {}:
return 'data'
ret.append({k: digui(graph[k])})
return ret

s = digui(iter_node)
print(s)

test(graph)