Reputation: 13
I have a dictionary-tree like this:
{ b : [e], a : [b,c], c : [], e : []}
How can I find the root(in this example 'a`) fast even if I have a very long dictionary?
Upvotes: 1
Views: 944
Reputation: 1363
In your example the variables (a, b, c, e) are not defined. Assuming you can replace them by strings (or even integers):
d = {'b':['e'], 'a':['b','c'], 'c':[], 'e':[]}
root = set(d).difference(*d.values()).pop()
print(root)
--> a
Upvotes: 1
Reputation: 726569
Walk the adjacency list, put each "from" node into a set of source nodes, and each of its corresponding "to" nodes into a set of destination nodes.
Subtracting the set of destinations from the set of sources will yield one of the following:
Here is how this works for your example:
source
: { b, a, c, e }
destination
: { e, b, c }
source \ destination
: { a }
Upvotes: 1