Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Sets solution in Clear category for How to Find Friends by Peter.White
'''
Find friends: Check if two entities are connected with each other through
common friends
'''
def check_connection(network, first, second):
'''
Input: network as a tuple of straight connections separated by hyphen
first as string
second as string
Output: True if first and second are connected, else False
'''
def find_neighbors(nodes):
neighbors = set()
for node in nodes:
for str8_conn in network:
if node in str8_conn:
# update neighbors while removing the node currently
# being checked
neighbors |= set(str8_conn.split('-')) - {node}
return neighbors
visited = {first}
future = find_neighbors(visited)
# if 'future' is a subset of 'neighbors', there were no new neighbors
while not future <= visited:
if second in future: # we have connection between first and second
return True
visited |= future
future |= find_neighbors(future)
return False
April 6, 2015
Comments: