简体   繁体   中英

Finding Root of Tree from List of Tuples

I am having issues writing a function that finds the root of a tree represented as a list of tuples in python.

Tree:

[(39, 38), (80, 70), (39, 42), (80, 91), (37, 22), (37, 39), (42, 45), (48, 37), (91, 85), (48, 60), (60, 80), (60, 50)]

I researched how to use classes for this but not sure if there is any kind of clever way to do this.

Just find the tuple start that is not in any tuple end:

lst = [(39, 38), (80, 70), (39, 42), (80, 91), (37, 22), (37, 39), (42, 45), (48, 37), (91, 85), (48, 60), (60, 80), (60, 50)]

rt = set([t[0] for t in lst if not t[0] in [t[1] for t in lst]])

print(rt)  # nothing links to 48 so it must be the root

Output

{48}

You can assign the t[1] loop to a variable if desired:

lst1 = [t[1] for t in lst]  # all end nodes
rt = set([t[0] for t in lst if not t[0] in lst1])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM