Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import unittest
- from collections import namedtuple, defaultdict
- # 6 possible colors
- COLORS = set("ROYGBP")
- Result = namedtuple("Result", ["exact_matches", "fuzzy_matches"])
- def evaluate_matches(solution, guess):
- # validate_input(solution)
- # validate_input(guess)
- num_total_matches = count_total_matches(solution, guess)
- num_exact_matches = count_exact_matches(solution, guess)
- return Result(exact_matches=num_exact_matches, fuzzy_matches=num_total_matches - num_exact_matches)
- def count_total_matches(solution, guess):
- # num_total_matches = 0
- count_solution = count_colors(solution)
- return sum([ min(num_color, count_solution[color]) for color, num_color in count_colors(guess).items() ])
- # for color, num_color in count_colors(guess).items():
- # num_total_matches += min(num_color, count_solution[color])
- # return num_total_matches
- def count_exact_matches(solution, guess):
- return sum([int(color_guess == color_solution) for color_guess, color_solution in zip(guess, solution)])
- def validate_input(color_string):
- if not isinstance(color_string, str):
- raise ValueError("Should be string")
- if len(color_string) != 4:
- raise ValueError("Should be of length 4")
- if not (set(color_string) <= COLORS):
- raise ValueError("String contains an invalid color")
- def count_colors(color_string):
- unique_colors = set(color_string)
- return defaultdict(int, dict([(color, count_occurrences_in_string(color_string, color)) for color in unique_colors]))
- def count_occurrences_in_string(color_string, color):
- return sum([int(color_string[i] == color) for i in range(len(color_string))])
- class TestMastermind(unittest.TestCase):
- def test_count_colors(self):
- self.assertEqual(count_colors("ROYY"), dict(R=1, O=1, Y=2))
- def xtest_validation(self):
- self.assertRaises(ValueError, evaluate_matches, "ROYG", "ROYX")
- def test_fuzzy_and_exact_match(self):
- solution = "ROYY"
- guesses = [
- ("OGGR", Result(exact_matches=0, fuzzy_matches=2)),
- ("ROYY", Result(exact_matches=4, fuzzy_matches=0)),
- ("YGGP", Result(exact_matches=0, fuzzy_matches=1)),
- ("YYGG", Result(exact_matches=0, fuzzy_matches=2)),
- ("ROOP", Result(exact_matches=2, fuzzy_matches=0)),
- ("YOOR", Result(exact_matches=1, fuzzy_matches=2)),
- ]
- for guess, result in guesses:
- self.assertEqual(evaluate_matches(solution, guess), result)
- if __name__ == "__main__":
- unittest.main()
Add Comment
Please, Sign In to add comment