Advertisement
vikramk3

Untitled

Jul 25th, 2014
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. def path_to_friend(network, user_A, user_B, path=None): #uses my second connection approach
  2.     if not path: path=[]
  3.     if (user_A or user_B) not in network.keys() :
  4.         return None
  5.     path=path + [user_A]
  6.     if user_B in get_connections(network,user_A):
  7.         return path + [user_B]
  8.     common_connections=second_conn_in_common(network,user_A,user_B)
  9.     if common_connections==0: # check if there is one connection between the two users
  10.         next_connections=get_connections(network,user_A)
  11.         for contact in next_connections:
  12.             if contact not in path:
  13.                 final=path_to_friend(network,contact,user_B,path)
  14.                 if final:
  15.                     return final
  16.         return None
  17.     elif common_connections>=1: # if one connection exists between two users, find the connection
  18.         path=path + [middle_contact(network,user_A,user_B)]+[user_B]
  19.         return path        
  20.        
  21. def second_conn_in_common(network, user_A, user_B): #find if user_B is a second connection of User A
  22.     if user_A not in network.keys():
  23.         return False
  24.     elif user_B not in network.keys():
  25.         return False
  26.     else:
  27.         count=0
  28.         for contact in network[user_A]['connected']:
  29.             if user_B in network[contact]['connected']:
  30.                 count = count + 1
  31.         return count
  32.        
  33.  
  34. def middle_contact(network,user_A,user_B): # find the contact between user_A and user_B
  35.     for contact in network[user_A]['connected']:
  36.         if user_B in network[contact]['connected']:
  37.             return contact
  38.  
  39.    
  40. print path_to_friend(network, "Debra", "Mercedes")
  41. print path_to_friend(network, "John", "Ollie")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement