Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. class Node:
  2. def __init__(self, id, color):
  3. self.id = id # int
  4. self.color = color # string
  5. self.adjacentNodes = set()
  6.  
  7. # actually this function return the unique string associated with the graph
  8. # that will be hashed with the function hash() in a second moment
  9. def new_hash(graph, queue=[]): # graph: list of Node
  10. if not queue: # first call: find the root of the tree
  11. graph.sort(key = lambda x: (len(x.adjacentNodes), x.color), reverse=True)
  12. groups = itertools.groupby(graph, key = lambda x: (len(x.adjacentNodes), x.color))
  13. roots = []
  14. result_hash = ''
  15.  
  16. for _, group in groups:
  17. roots = [x for x in group]
  18. break # I just need the first (the candidates roots)
  19.  
  20. temp_hashes = []
  21.  
  22. for node in roots:
  23. temp_queue = [node.id]
  24. temp_hash = node.color + str(len(node.adjacentNodes)) + str(temp_queue.index(node.id))
  25. temp_hash += new_hash(list(node.adjacentNodes), temp_queue)
  26. temp_hashes.append((node, temp_hash, temp_queue))
  27.  
  28. temp_hashes.sort(key = lambda x: x[1], reverse=True)
  29. queue = temp_hashes[0][2]
  30. result_hash += temp_hashes[0][1]
  31. result_hash += new_hash(list(temp_hashes[0][0].adjacentNodes), queue=queue)
  32. else:
  33. graph.sort(key = lambda x: (len(x.adjacentNodes), x.color), reverse=True)
  34. groups = itertools.groupby(graph, key = lambda x: (len(x.adjacentNodes), x.color))
  35. grouped_nodes = []
  36. result_hash = ''
  37.  
  38. for _, group in groups:
  39. grouped_nodes.append([x for x in group])
  40.  
  41. for group in grouped_nodes:
  42. while len(group) > 0:
  43. temp_hashes = []
  44.  
  45. for node in group:
  46. if node.id in queue:
  47. temp_hash = node.color + str(len(node.adjacentNodes)) + str(queue.index(node.id))
  48. temp_hashes.append((node, temp_hash, queue))
  49. else:
  50. temp_queue = queue[:]
  51. temp_queue.append(node.id)
  52. temp_hash = node.color + str(len(node.adjacentNodes)) + str(temp_queue.index(node.id))
  53. temp_hash += new_hash(list(node.adjacentNodes), queue=temp_queue)
  54. temp_hashes.append((node, temp_hash, temp_queue))
  55.  
  56. temp_hashes.sort(key = lambda x: x[1], reverse=True)
  57. queue = temp_hashes[0][2]
  58. result_hash += temp_hashes[0][1]
  59. group.remove(temp_hashes[0][0])
  60.  
  61. return result_hash
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement