Skip to content

Instantly share code, notes, and snippets.

@nsmgr8
Last active April 14, 2020 08:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsmgr8/23bc8fb383849d881d2d9ed84e1565e8 to your computer and use it in GitHub Desktop.
Save nsmgr8/23bc8fb383849d881d2d9ed84e1565e8 to your computer and use it in GitHub Desktop.
Quiz from facebook python BD group
from typing import NamedTuple, Callable
class KeyCombination(NamedTuple):
first: int
second: int
third: int
def __str__(self):
return f'{self.first}{self.second}{self.third}'
def match_correct(
rule_digits: KeyCombination,
number_of_correct_digits: int,
at_right_place: bool = False
) -> Callable[[KeyCombination], bool]:
"""
Rule creator
:param rule_digits: a tuple of digits that makes the rule
:param number_of_correct_digits: number of correct digits should be matched
in the given tuple of digits
:param at_right_place: if True, then the digit must be matched in the same
place it is given in the rule; if False, it must not match in the same
place in the rule
:return: a function that takes a guess tuple and returns True if rule
matches; False otherwise
"""
def match(guess: KeyCombination) -> bool:
"""
The match maker
"""
matched_places = []
for guess_digit_idx, guess_digit in enumerate(guess):
if guess_digit in rule_digits:
at_same_place = guess_digit_idx == rule_digits.index(guess_digit)
matched_places.append(at_same_place == at_right_place)
return len(matched_places) == number_of_correct_digits and all(matched_places)
return match
rules = [
match_correct(KeyCombination(1, 4, 7), 1),
match_correct(KeyCombination(1, 8, 9), 1, True),
match_correct(KeyCombination(9, 6, 4), 2),
match_correct(KeyCombination(5, 2, 3), 0),
match_correct(KeyCombination(2, 8, 6), 1),
]
for number in range(1000):
guess = KeyCombination(*[int(c) for c in f'{number:03d}'])
for rule in rules:
if not rule(guess):
# a rule is broken; no need to go further
break
else:
# all rules are satisfied a match is found
print(guess)
@nsmgr8
Copy link
Author

nsmgr8 commented Apr 14, 2020

Added type hints and docstrings for readability and explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment