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
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=2matches the puzzle: each islander is one of two types, so each step splits into two cases.max_depth=4gives room to assume a case, follow it through the other two islanders, and state the answer.evaluation_criteriatells 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.
Cost
With nomax_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.