Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using set union solution in Clear category for How to Find Friends by johnhaines
def check_connection(network, first, second):
##print ("Network ", network, " First ", first, " Second ", second)
#
# Build a list containing sets of each pair in a connection.
#
list_of_sets = []
for i in network:
# get the values in each instance of network into a set without the -
list_of_sets.append(set(i.split("-")))
# Seed a new set with the first name.
set_first = set([first])
#
# Build up this set by loop through list of sets.
# Note a for loop will not work - as you may be extending the set within an iteration.
#
counter = 1
while counter <= len(set_first):
for i in set_first:
for s in list_of_sets:
if i in s:
set_first = set_first.union(s)
# removing is not necessary but shrinks the number of iterations
list_of_sets.remove(s)
##print("End of loop i ", set_first)
counter += 1
# All items linked, directly or indirectly to first are now in set_first
#
if second in set_first:
return True
else:
return False
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"scout2", "scout3") == True, "Scout Brotherhood"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"super", "scout2") == True, "Super Scout"
assert check_connection(
("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
"scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
"dr101", "sscout") == False, "I don't know any scouts."
July 19, 2014