Last active
August 27, 2021 07:51
-
-
Save alvinwan/28a70140e4f3c6a556f8d54ad475650b to your computer and use it in GitHub Desktop.
Einstein riddle solver in Python, for Skillshare student question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
finalized = [{}, {}, {}, {}, {}] # 5 houses, with no properties set yet | |
# 1. express all constraints | |
constraints = [ | |
[{'nationality': 'Brit', 'color': 'red'}], # the Brit lives in the red house | |
[{'drink': 'coffee', 'color': 'green', 'offset': 0}, {'color': white', 'offset': 1}], | |
... | |
] | |
# 2. iteratively... | |
while constraints: # if any constraints are left | |
for constraint in constraints: | |
possible_positions = get_possible_positions(finalized, constraint) | |
if len(possible_positions) == 1: | |
apply_constraint(finalized[possible_positions[0]], constraint) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_possible_positions(finalized, constraint): | |
"""Collect all possible positions for this constraint's house to live in.""" | |
possible_positions = [] | |
for idx_house in range(len(finalized)): | |
if is_possible_position(finalized, idx_house, constraint): | |
possible_positions.append(i) | |
return possible_positions | |
def is_possible_position(finalized, idx_start, constraint): | |
"""Check whether this is a valid starting position for all the houses specified in the constraint. | |
In the 1-column case, check if this is a valid position for the 1-column constraint. | |
""" | |
for column in constraint: | |
idx_house = idx_start + column.get('offset', 0) # get the offset if it exists. If no offset key, use 0. | |
if is_conflicting_constraint(finalized[idx_house], col): | |
return False | |
return True | |
def is_conflicting_constraint(col1, col2): | |
"""Check if these two columns can co-exist. | |
- For example, if one specifies color and the other specifies, they can coexist. | |
- However, if both specify nationality, they cannot co-exist. | |
""" | |
for key in col1: | |
if key in col2: | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment