A recursive backtracking solver for a generalized version of the Game of 24.
print(solve_24([1, 2, 3, 4])) # Output: (1 + 2 + 3) * 4
print(solve_24([3, 3, 8, 8])) # Output: 8 / (3 - (8 / 3))
print(solve_24([1, 5, 5, 5])) # Output: 5 * (5 - (1 / 5))
print(solve_24([5, 6, 7, 8])) # Output: (5 + 7) * (8 - 6)The solver finds solutions by repeatedly shrinking the list of numbers step-by-step:
- Pick any 2 numbers from the list.
- Combine them using an operation (
+,-,*,/) to create a single, parenthesized expression (for example,3and8combine into(8 / 3)). - Put the result back in the list, replacing the two original numbers.
- Repeat this process recursively until only 1 final number remains.
- Success: If the final remaining number equals the target, the algorithm returns the built-up math string.
- Safety: If a combination requires dividing by zero, the solver immediately skips it and tries a different path.
© Copyright 2026 Blake Rayvid. All rights reserved.