问题
So I'm trying to find indirect relations in a dictionary but I can't seem to find a general code for my program: this is what I have
#find if A is related to E
data = {"A": {"B": 5, "C": 7}, "B": {"E": 8}, "C": {}, "D": {}, "E": {"D": 9}}
if "E" in data["A"]:
result = True
if "E" in data["B"] or "D" in data["C"]:
result = True
else:
result = False
print(result)
#output = True because "E" is in data["A"]
For this one example it works and ofcourse I've could generalize this with x's and y's but if I have a data variable with a complexer dictionary it wouldn't work. Maybe recursive code or a for loop? If somebody could help, it would be very much appreciated.
Thank you in advance
回答1:
for k,v in data.items():
for l,u in data.items():
if k in u:
print(f"{k} in {u}")
so that the desired function might be :
def has_indirect_rel(dico):
for k,v in dico.items():
for l,u in dico.items():
if k in u: return True
return False
回答2:
First, the numbers aren't of interest to the problem at hand, so let's reduce the data from dict
of dictionaries to dict
of sets:
data = {'A': {'B', 'C'}, 'B': {'E'}, 'C': {}, 'D': {}, 'E': {'D'}}
We could search the data recursively:
def has_relation(mapping, a, b):
if b in mapping[a]:
return True
for c in mapping[a]:
if has_relation(mapping, c, b):
return True
return False
print(has_relation(data, 'A', 'D'))
print(has_relation(data, 'A', 'E'))
print(has_relation(data, 'A', 'F'))
来源:https://stackoverflow.com/questions/65263046/how-to-find-indirect-relation-python