Skip to content

Instantly share code, notes, and snippets.

@timendum
Last active March 18, 2026 15:22
Show Gist options
  • Select an option

  • Save timendum/328086fc7ee29b7a901725308108716a to your computer and use it in GitHub Desktop.

Select an option

Save timendum/328086fc7ee29b7a901725308108716a to your computer and use it in GitHub Desktop.
Make 10 and generic four numbers to reach a target
"""
This function solves a "make 10" puzzle:
given a string of digits (e.g., "3596"),
it finds all possible arithmetic expressions using those four digits (each used exactly once)
and the operators +, -, *, / that evaluate to 10.
It also considers different placements of parentheses to account for order-of-operations variations.
It's a brute-force solver for the "four numbers to reach 10" number game.
"""
from itertools import combinations, product
def find_solution(n, ops="+-*/"):
for x, y, w, z in permutations(n):
for (a, b, c) in product(ops, repeat=3):
for opar in ["( ", " ( ", " (", " "]:
for cpar in [") ", " ) ", " )", " "]:
if opar == " ( " and cpar == ") ":
continue
if opar == " (" and cpar == " ) ":
continue
if opar == "( " and cpar == " )":
continue
expr = f"{opar[0]}{x} {a} {opar[1]}{y}{cpar[0]} {b} {opar[2]}{w}{cpar[1]} {c} {z}{cpar[2]}"
try:
if eval(expr) == 10:
print(expr.replace(" ", " ").strip())
except (ZeroDivisionError, SyntaxError):
pass
# How to use
find_solution("3596", "+-*/")
"""
For each valid combination of 0-9,
it returns an arithmetic math expression that evaluates to `n`.
It finds all combinations of four single-digit numbers (0-9)
that can be combined using basic arithmetic operators (+, -, *, /) and
optional placements of parentheses to account for order-of-operations,
to produce a given target value `n`.
"""
from itertools import combinations_with_replacement, permutations, product
def four_digits_solutions(n, only_one=True, par=True):
solutions = {}
for xxxx in combinations_with_replacement(range(10), 4):
for x, y, w, z in permutations(xxxx):
if only_one and xxxx in solutions:
break
for a, b, c in product("+-*/", repeat=3):
if only_one and xxxx in solutions:
break
for opar in ["( ", " ( ", " (", " "] if par else (" ",):
if only_one and xxxx in solutions:
break
for cpar in [") ", " ) ", " )", " "] if par else (" ",):
if opar == " ( " and cpar == ") ":
continue
if opar == " (" and cpar == " ) ":
continue
if opar == "( " and cpar == " )":
continue
expr = f"{opar[0]}{x} {a} {opar[1]}{y}{cpar[0]} {b} {opar[2]}{w}{cpar[1]} {c} {z}{cpar[2]}"
try:
if eval(expr) == n:
solutions[xxxx] = expr.replace(" ", " ").strip()
break
except (ZeroDivisionError, SyntaxError):
pass
return solutions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment