Skip to main content
Logic puzzles are case analysis: assume one islander’s type, follow the consequences, and drop the case when it contradicts a statement. That is what depth-first search does. It commits to the most promising case, and when the evaluator finds a contradiction and prunes it, the search backtracks to the next one.

Prerequisites

TreeOfThoughts is not in swarms 15.0.3 on PyPI, so install from GitHub until the next release.

The code

knights_and_knaves.py
It prints who is which, the deductions on the path that solved it, and what the search cost.

What the settings do

  • search_algorithm="dfs" expands the best case first and returns the first solution that survives evaluation. A pruned case sends the search back to the next one.
  • num_thoughts=2 matches the puzzle: each islander is one of two types, so each step splits into two cases.
  • max_depth=4 gives room to assume a case, follow it through the other two islanders, and state the answer.
  • evaluation_criteria tells the evaluator that a contradicted case must be ruled out, so it scores low and is pruned rather than kept.

Check the answer

  • Assume A is a knave. Then B is a knight, so exactly one islander is a knight: B. That makes C a knave, so C’s statement is false and B and C are the same kind. But B is a knight and C is a knave. Contradiction.
  • So A is a knight and B is a knave. B’s statement is false, so the number of knights is not one. A is already a knight, so C must be a knight too. Then C’s statement, that B and C differ, is true, which fits.
The answer is A is a knight, B is a knave, C is a knight.

Cost

With no max_expansions, DFS can expand up to 1 + 2 + 4 + 8 = 15 nodes here, for at most 46 model calls. It stops at the first solution, so a search that rules out the wrong case early costs far less. Set max_expansions to cap it: max_expansions=5 bounds this search at 16 calls. See Cost for the formula.

Next

Number theory

BFS with a beam of 3 and averaged ratings.

TreeOfThoughts reference

Every parameter, strategy, and result field.