The program should use this data to calculate the full set of dependencies. For example, looking at B, we see it directly depends on C and E. C in turn relies on G, E relies on F, and F relies on H. This means that B ultimately relies on C, E, F, G, and H.
input_data ={
"A":["B","C"],
"B":["C","E"],
"C":["G"],
"D":["A","F"],
"E":["F"],
"F":["H"]
}
output will be the reference of for all of dependent values.
output ={
"A":["B","C","E","F","G","H"],
"B":["C","E","F","G","H"],
"C":["G"],
"D":["A","B","C","E","F","G","H"],
"E":["F","H"],
"F":["H"]
}
If possible I want try it with recursion
I tried something like this
import copy
output = copy.deepcopy(input_data)
def rec_update(key, values):
for value in values:
if not input_data .get(value):
if not value in output[key]:
output[key].append(value)
else:
rec_update(value, input_data .get(value))
for key, values in input_data .items():
rec_update(key, values)
Here is my suggestion. Firstly we create a function that iterates through the input_data for x, adding new child items. It stops when no new child items are found. Then we apply this function on all keys of input_data:
input_data ={
"A":["B","C"],
"B":["C","E"],
"C":["G"],
"D":["A","F"],
"E":["F"],
"F":["H"]
}
def f(x):
res=[]
new=input_data[x]
while new!=[]:
res.extend([i for i in new if i not in res])
temp=[]
for i in res:
if input_data.get(i):
temp.extend(input_data.get(i))
new=[k for k in temp if k not in res]
return res
output={i:f(i) for i in input_data}
print(output)
Result:
{'A': ['B', 'C', 'E', 'G', 'F', 'H'], 'B': ['C', 'E', 'G', 'F', 'H'], 'C': ['G'], 'D': ['A', 'F', 'B', 'C', 'H', 'E', 'G'], 'E': ['F', 'H'], 'F': ['H']}
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.