Guest User

Untitled

a guest
Apr 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. import unittest
  2. from collections import namedtuple, defaultdict
  3.  
  4. # 6 possible colors
  5. COLORS = set("ROYGBP")
  6. Result = namedtuple("Result", ["exact_matches", "fuzzy_matches"])
  7.  
  8. def evaluate_matches(solution, guess):
  9. # validate_input(solution)
  10. # validate_input(guess)
  11. num_total_matches = count_total_matches(solution, guess)
  12. num_exact_matches = count_exact_matches(solution, guess)
  13. return Result(exact_matches=num_exact_matches, fuzzy_matches=num_total_matches - num_exact_matches)
  14.  
  15. def count_total_matches(solution, guess):
  16. # num_total_matches = 0
  17. count_solution = count_colors(solution)
  18. return sum([ min(num_color, count_solution[color]) for color, num_color in count_colors(guess).items() ])
  19. # for color, num_color in count_colors(guess).items():
  20. # num_total_matches += min(num_color, count_solution[color])
  21. # return num_total_matches
  22.  
  23. def count_exact_matches(solution, guess):
  24. return sum([int(color_guess == color_solution) for color_guess, color_solution in zip(guess, solution)])
  25.  
  26. def validate_input(color_string):
  27. if not isinstance(color_string, str):
  28. raise ValueError("Should be string")
  29.  
  30. if len(color_string) != 4:
  31. raise ValueError("Should be of length 4")
  32.  
  33. if not (set(color_string) <= COLORS):
  34. raise ValueError("String contains an invalid color")
  35.  
  36. def count_colors(color_string):
  37. unique_colors = set(color_string)
  38. return defaultdict(int, dict([(color, count_occurrences_in_string(color_string, color)) for color in unique_colors]))
  39.  
  40. def count_occurrences_in_string(color_string, color):
  41. return sum([int(color_string[i] == color) for i in range(len(color_string))])
  42.  
  43. class TestMastermind(unittest.TestCase):
  44. def test_count_colors(self):
  45. self.assertEqual(count_colors("ROYY"), dict(R=1, O=1, Y=2))
  46.  
  47. def xtest_validation(self):
  48. self.assertRaises(ValueError, evaluate_matches, "ROYG", "ROYX")
  49.  
  50. def test_fuzzy_and_exact_match(self):
  51. solution = "ROYY"
  52. guesses = [
  53. ("OGGR", Result(exact_matches=0, fuzzy_matches=2)),
  54. ("ROYY", Result(exact_matches=4, fuzzy_matches=0)),
  55. ("YGGP", Result(exact_matches=0, fuzzy_matches=1)),
  56. ("YYGG", Result(exact_matches=0, fuzzy_matches=2)),
  57. ("ROOP", Result(exact_matches=2, fuzzy_matches=0)),
  58. ("YOOR", Result(exact_matches=1, fuzzy_matches=2)),
  59. ]
  60. for guess, result in guesses:
  61. self.assertEqual(evaluate_matches(solution, guess), result)
  62.  
  63.  
  64. if __name__ == "__main__":
  65. unittest.main()
Add Comment
Please, Sign In to add comment