Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Mind Switcher by ignalion
def mind_switcher(journal):
# Firstly, make dict with current body: mind status
robots = {}
for pair in journal:
body, mind = pair
robots[body], robots[mind] = robots.get(mind, mind), robots.get(body, body)
res = ()
swap = False
# Then it's pretty simple. If we draw oriented graph for all body: mind
# pairs we can see many graphs with 1, 2 or more nodes. We take any node
# and then just change nikola with this node, sophia with 2nd
# then again nikola with 2nd node (2nd node now has it's own mind) and
# sophia with next node. If sophia now has mind of the first node - it's
# done. If not, we just replace sophia node with every next node (again,
# placing it's own mind to one) until we find the node that points to the
# first.
while robots:
first, mind = robots.popitem()
if first == mind:
continue
res += ({'nikola', first}, {'sophia', mind})
body, mind = mind, robots.pop(mind)
res += ({'nikola', body}, {'sophia', mind})
while mind != first:
body, mind = mind, robots.pop(mind)
res += ({'sophia', mind},)
swap = not swap
# Every graph processing changes sophia's and nikola's minds. If there're
# odd number of graphs, we should just change sophia and nikola
if swap:
res += ({'sophia', 'nikola'},)
return res
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
def check_solution(func, data):
robots = {"nikola": "nikola", "sophia": "sophia"}
switched = []
for pair in data:
switched.append(set(pair))
r1, r2 = pair
robots[r1], robots[r2] = robots.get(r2, r2), robots.get(r1, r1)
result = func(data)
if not isinstance(result, (list, tuple)) or not all(isinstance(p, set) for p in result):
print("The result should be a list/tuple of sets.")
return False
for pair in result:
if len(pair) != 2:
print(1, "Each pair should contain exactly two names.")
return False
r1, r2 = pair
if not isinstance(r1, str) or not isinstance(r2, str):
print("Names must be strings.")
return False
if r1 not in robots.keys():
print("I don't know '{}'.".format(r1))
return False
if r2 not in robots.keys():
print("I don't know '{}'.".format(r2))
return False
if set(pair) in switched:
print("'{}' and '{}' already were switched.".format(r1, r2))
return False
switched.append(set(pair))
robots[r1], robots[r2] = robots[r2], robots[r1]
for body, mind in robots.items():
if body != mind:
print("'{}' has '{}' mind.".format(body, mind))
return False
return True
#assert check_solution(mind_switcher, ({"scout", "super"},))
#assert check_solution(mind_switcher, ({'hater', 'scout'}, {'planer', 'hater'}))
#assert check_solution(mind_switcher, ({'scout', 'driller'}, {'scout', 'lister'},
# {'hater', 'digger'}, {'planer', 'lister'}, {'super', 'melter'}))
assert check_solution(mind_switcher, ({'digger', 'melter'}, {'melter', 'planer'}, {'digger', 'planer'}))
Dec. 19, 2014
Comments: