Guest User

garrab

a guest
Jan 23rd, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. '''
  2. Complexity: O(m log(n))
  3.  
  4. m is the number of uf operations while n is the number of objects
  5. '''
  6. from collections import defaultdict
  7. from itertools import combinations
  8.  
  9. def f(x, y):
  10.     c1 = ((x == "Berlin") and (y == "Hamburg")) or ((y=="Hamburg") and (x=="Berlin"))
  11.     c2 = ((x == "Hamburg") and (y == "Bremen")) or ((y=="Bremen") and (x=="Hamburg"))
  12.     return c1 or c2
  13.  
  14. def union(data, i, j):
  15.     pi, pj = find(data, i), find(data, j)
  16.     if pi != pj:
  17.         data[pi] = pj
  18.  
  19. def find(data, i):
  20.     if data[i] != i:
  21.         data[i] = find(data, data[i])
  22.     return data[i]
  23.  
  24.  
  25. '''
  26. ## Step 1
  27. Berlin: Berlin
  28. Hamburg: Hamburg
  29. Munich: Munich
  30. Bremen: Bremen
  31. ## Step 2 = f(Berlin, Hamburg) = True
  32. Berlin: Berlin
  33. Hamburg: Berlin
  34. Munich: Munich
  35. Bremen: Bremen
  36. ...etc
  37. '''
  38. data = defaultdict(str)
  39. cities = ["Berlin", "Hamburg", "Munich", "Bremen"]
  40.  
  41. # Initially all cities are in a separate group
  42. for c in cities:
  43.     data[c] = c
  44.  
  45. # combinations -> O(N^2) where N is number of cities
  46. # Proof:
  47. # combinations formula => nCr => (n! / (r!(n-r)!)) where r = 2
  48. #                               n(n-1) / 2 = O(n^2)
  49.  
  50. for i,j in combinations(cities,2):
  51.     if f(i,j):
  52.         union(data, i, j)
  53.  
  54. print (data)
  55. groups = defaultdict(list)
  56. for k in data:
  57.     groups[data[k]].append(k)
  58.  
  59. print (groups)
Advertisement
Add Comment
Please, Sign In to add comment