Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. from collections import defaultdict
  2.  
  3. def find_graph() :
  4.     graphs = defaultdict(int)
  5.     planets = set()
  6.     with open('input.txt') as file :
  7.         for line in file :
  8.             stuff = line.strip().split(")")
  9.             x, y = stuff[0], stuff[1] #y orbits x
  10.             graphs[(x,y)] = 1
  11.             planets.add(y)
  12.     return graphs, planets
  13.  
  14.  
  15. def find_depth(tree, node) :
  16.     try :
  17.         parent = next(key for key, value in tree.items() if key[1] == node and value == 1)[0]
  18.         return 1 + find_depth(tree, parent)
  19.     except :
  20.         return 0
  21.  
  22. graphs, planets = find_graph()
  23.  
  24. def findSum(graph=graphs, planet=planets) :
  25.     sum=0
  26.     for node in planet :
  27.         sum += find_depth(graph, node)
  28.    
  29.     print(sum)
  30.  
  31. #findSum()
  32.  
  33. def findTransfers(tree=graphs, node1='YOU', node2='SAN') : #Find distance between 2 nodes on a tree
  34.     #find ancestors of nodes
  35.     tempNode = node1
  36.     ancestors1 = []
  37.     ancestors2 = []
  38.     while True :
  39.         try :
  40.             parent = next(key for key, value in tree.items() if key[1] == tempNode and value == 1)[0]
  41.             ancestors1.append(parent)
  42.             tempNode = parent
  43.         except :
  44.             break
  45.    
  46.     tempNode = node2
  47.     while True :
  48.         try :
  49.             parent = next(key for key, value in tree.items() if key[1] == tempNode and value == 1)[0]
  50.             ancestors2.append(parent)
  51.             tempNode = parent
  52.         except :
  53.             break
  54.  
  55.     for node in ancestors1 :
  56.         if node in ancestors2 :
  57.             common = node
  58.             break
  59.     print(common)
  60.  
  61.     length =  ancestors1.index(common) + ancestors2.index(common) - 1
  62.     print(length)
  63.  
  64.  
  65. findTransfers()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement