fork download
  1. def get_chain(d):
  2. nodes = {}
  3. # create linked list nodes
  4. for name, (end, start) in d.items():
  5. nodes[start] = [name, (start, end), None]
  6.  
  7. # build the linked list by looking up other nodes
  8. for node in list(nodes.values()):
  9. start, end = node[1]
  10. node[2] = nodes.pop(end, None)
  11.  
  12. # there should be only a single node left in nodes
  13. head = next(iter(nodes.values()), None)
  14.  
  15. # yield out the chain values
  16. while head is not None:
  17. start, end = head[1]
  18. yield start
  19. # if last node, yield the end value
  20. if head[2] is None:
  21. yield end
  22. head = head[2]
  23.  
  24. print(list(get_chain({
  25. 'A': ['tg', 17],
  26. 'B': [59, 60],
  27. 'C': [60, 61],
  28. 'D': [57, 'tt'],
  29. 'E': [61, 'tg'],
  30. 'F': ['tt', 59]
  31. })))
Success #stdin #stdout 0.09s 14144KB
stdin
Standard input is empty
stdout
[17, 'tg', 61, 60, 59, 'tt', 57]