Advertisement
sreejith2904

Transitive Relationships

May 1st, 2021
799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. def transitive_cloure(array):
  2.     new_list = [set(array.pop(0))]  # initialize first set with value of index `0`
  3.  
  4.     for item in array:
  5.         for i, s in enumerate(new_list):
  6.             if any(x in s for x in item):
  7.                 new_list[i] = new_list[i].union(item)
  8.                 break
  9.         else:
  10.             new_list.append(set(item))
  11.     return new_list
  12.  
  13.  
  14. def countGroups(arr):
  15.    
  16.     inp = [list(x) for x in arr]
  17.    
  18.     size = len(inp)
  19.    
  20.     relationships = []
  21.    
  22.     for i in range(size):
  23.         for j in range(size):
  24.             if (i != j) and (inp[i][j] == '1'):
  25.                 if ((i,j) not in relationships) and ((j,i) not in relationships):
  26.                     relationships.append((i,j))
  27.                    
  28.     transitive_relationships = transitive_cloure(relationships)
  29.  
  30.     return len(transitive_relationships)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement