My solutions to Harvard's online course CS50AI, An Introduction to Machine Learning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.1 KiB

4 years ago
  1. from logic import *
  2. AKnight = Symbol("A is a Knight")
  3. AKnave = Symbol("A is a Knave")
  4. BKnight = Symbol("B is a Knight")
  5. BKnave = Symbol("B is a Knave")
  6. CKnight = Symbol("C is a Knight")
  7. CKnave = Symbol("C is a Knave")
  8. # Puzzle 0
  9. # A says "I am both a knight and a knave."
  10. knowledge0 = And(
  11. Not(And(AKnave, AKnight)),
  12. Or(AKnave, AKnight),
  13. Implication(AKnight, And(AKnave, AKnight))
  14. )
  15. # Puzzle 1
  16. # A says "We are both knaves."
  17. # B says nothing.
  18. knowledge1 = And(
  19. Not(And(AKnave, AKnight)), Or(AKnave, AKnight),
  20. Not(And(BKnave, BKnight)), Or(BKnave, BKnight),
  21. Implication(AKnight, And(AKnave, BKnave)),
  22. Implication(AKnave, Not(And(AKnave, BKnave)))
  23. )
  24. # Puzzle 2
  25. # A says "We are the same kind."
  26. # B says "We are of different kinds."
  27. knowledge2 = And(
  28. Not(And(AKnave, AKnight)), Or(AKnave, AKnight),
  29. Not(And(BKnave, BKnight)), Or(BKnave, BKnight),
  30. Implication(AKnight, And(AKnight, BKnight)),
  31. Implication(BKnave, And(AKnight, BKnight)),
  32. Implication(BKnight, And(Not(And(BKnight, AKnight)), Not(And(BKnave, AKnave))))
  33. )
  34. # Puzzle 3
  35. # A says either "I am a knight." or "I am a knave.", but you don't know which.
  36. # B says "A said 'I am a knave'."
  37. # B says "C is a knave."
  38. # C says "A is a knight."
  39. knowledge3 = And(
  40. Not(And(AKnave, AKnight)), Or(AKnave, AKnight),
  41. Not(And(BKnave, BKnight)), Or(BKnave, BKnight),
  42. Not(And(CKnave, CKnight)), Or(CKnave, CKnight),
  43. Implication(AKnave, AKnight),
  44. Biconditional(AKnave, BKnight),
  45. Biconditional(BKnave, CKnight),
  46. Biconditional(AKnight, CKnight)
  47. )
  48. def main():
  49. symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave]
  50. puzzles = [
  51. ("Puzzle 0", knowledge0),
  52. ("Puzzle 1", knowledge1),
  53. ("Puzzle 2", knowledge2),
  54. ("Puzzle 3", knowledge3)
  55. ]
  56. for puzzle, knowledge in puzzles:
  57. print(puzzle)
  58. if len(knowledge.conjuncts) == 0:
  59. print(" Not yet implemented.")
  60. else:
  61. for symbol in symbols:
  62. if model_check(knowledge, symbol):
  63. print(f" {symbol}")
  64. if __name__ == "__main__":
  65. main()