Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
two solutions 5 & 13 lines solution in Clear category for The Einstein Problem-Lite by CDG.Axel
from itertools import product
QUESTIONS = {"number": {'1', '2', '3', '4', '5'},
"color": {'blue', 'green', 'red', 'white', 'yellow'},
"nationality": {'Brit', 'Dane', 'German', 'Norwegian', 'Swede'},
"beverage": {'beer', 'coffee', 'milk', 'tea', 'water'},
"cigarettes": {'Rothmans', 'Dunhill', 'Pall Mall', 'Winfield', 'Marlboro'},
"pet": {'cat', 'bird', 'dog', 'fish', 'horse'}}
def answer(relations, question):
owner, group = question.split('-')
relations = [x.split('-') for x in relations]
for pers in product(*QUESTIONS.values()):
if all((x in pers) == (y in pers) for x, y in relations) and owner in pers:
return pers[list(QUESTIONS).index(group)]
"""
# my first solution without product
def answer(relations, question):
# reform list of strings to list of sets
relations = [set(x.split('-')) for x in relations]
# init result with set of numbers
clusters = [{x} for x in QUESTIONS['number']]
while True:
# append all linked items to clusters
[[c.update(rel) for rel in relations if c & rel] for c in clusters]
for i in QUESTIONS:
# find element of question that not in cluster
elem = QUESTIONS[i].copy()
[elem.difference_update(c) for c in clusters]
# if we have one - add it to cluster
if len(elem) == 1:
[cl.update(elem) for cl in clusters if not cl & QUESTIONS[i]]
# stop if cluster contain all questions
if all([len(cl) == len(QUESTIONS) for cl in clusters]):
break
owner, group = question.split('-')
return [cl & QUESTIONS[group] for cl in clusters if owner in cl][0].pop()
"""
if __name__ == '__main__':
assert answer(('Norwegian-Dunhill', 'Marlboro-blue', 'Brit-3',
'German-coffee', 'beer-white', 'cat-water',
'horse-2', 'milk-3', '4-Rothmans',
'dog-Swede', 'Norwegian-1', 'horse-Marlboro',
'bird-Brit', '4-green', 'Winfield-beer',
'Dane-blue', '5-dog', 'blue-horse',
'yellow-cat', 'Winfield-Swede', 'tea-Marlboro'),
'fish-color') == 'green' # What is the color of the house where the Fish lives?
assert answer(('Norwegian-Dunhill', 'Marlboro-blue', 'Brit-3',
'German-coffee', 'beer-white', 'cat-water',
'horse-2', 'milk-3', '4-Rothmans',
'dog-Swede', 'Norwegian-1', 'horse-Marlboro',
'bird-Brit', '4-green', 'Winfield-beer',
'Dane-blue', '5-dog', 'blue-horse',
'yellow-cat', 'Winfield-Swede', 'tea-Marlboro'),
'tea-number') == '2' # What is the number of the house where tea is favorite beverage?
assert answer(('Norwegian-Dunhill', 'Marlboro-blue', 'Brit-3',
'German-coffee', 'beer-white', 'cat-water',
'horse-2', 'milk-3', '4-Rothmans',
'dog-Swede', 'Norwegian-1', 'horse-Marlboro',
'bird-Brit', '4-green', 'Winfield-beer',
'Dane-blue', '5-dog', 'blue-horse',
'yellow-cat', 'Winfield-Swede', 'tea-Marlboro'),
'Norwegian-beverage') == 'water' # What is the favorite beverage of the Norwegian man?
Sept. 16, 2021