Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for How to Find Friends by masamish
class Buckets():
def __init__(self):
self.bkt = []
def find(self, scout):
for i in self.bkt:
if scout in i:
return self.bkt.index(i)
return -1
def append(self, first, second):
f = self.find(first)
s = self.find(second)
if f == -1 and s == -1:
bucket = set()
bucket.add(first)
bucket.add(second)
self.bkt.append(bucket)
elif f >= 0 and s >= 0:
if f != s:
# print(first,second,f,s)
self.merge(f, s)
else:
pass
elif f == -1 and s >= 0:
self.bkt[s].add(first)
else:
self.bkt[f].add(second)
# print(self)
def merge(self, i, j):
if i > j:
i, j = j, i
self.bkt[i] = self.bkt[i].union(self.bkt[j])
self.bkt = self.bkt[:j] + self.bkt[j+1:]
def __repr__(self):
return str(self.bkt)
def check_connection(network, first, second):
# create buckets
buckets = Buckets()
for i in network:
a, b = i.split('-')
buckets.append(a, b)
# print(buckets)
f = buckets.find(first)
s = buckets.find(second)
return f == s
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."
assert check_connection(("scout1-scout3","plane1-robin","scout3-sscout","scout1-base","pingin-scout1","sscout-base","scout3-plane1","scout3-robin","plane1-nikola","plane1-pingin","base-scout3","plane1-sobhia","base-pingin","scout3-sobhia","robin-stevan","robin-base","nikola-robin","sobhia-sscout","stevan-sscout","robin-sobhia","robin-sscout","pingin-sscout","scout3-nikola","nikola-base","plane1-scout1","plane1-base","sscout-plane1","sobhia-scout1","sscout-scout1","robin-pingin","pingin-stevan","pingin-sobhia","scout3-pingin","nikola-sscout","nikola-pingin","stevan-base","stevan-scout1","scout1-nikola","nikola-sobhia","stevan-sobhia","stevan-scout3","scout1-robin","nikola-stevan","sobhia-base","stevan-plane1",),"pingin","sobhia") == True
Jan. 27, 2015
Comments: