Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilobellini/246c9d815d662ef364e6299a705c670e to your computer and use it in GitHub Desktop.
Save danilobellini/246c9d815d662ef364e6299a705c670e to your computer and use it in GitHub Desktop.
Smallest quadratic equations that answers a viral math puzzle using Sympy
#!/usr/bin/python
# By Danilo J. S. Bellini
# 2016-05-02 17:31:56 BRT
"""
Smallest quadratic equations that answers the viral math puzzle below,
using Sympy
1 + 4 = 5
2 + 5 = 12
3 + 6 = 21
8 + 11 = ?
"""
from sympy import symbols, solve, Eq
from itertools import combinations
A, B, result, x, y, z = symbols("A B result x y z")
data = [(1, 4, 5), (2, 5, 12), (3, 6, 21)]
dict_data = [dict(zip([A, B, result], triple)) for triple in data]
wanted = {A: 8, B: 11}
base = [1, A, B, A*A, A*B, B*B]
unks = [x, y, z]
sspaces = combinations(base, len(unks))
eqs = [sum(a * b for a, b in zip(dims, unks)) for dims in sspaces]
solvit = lambda eq: solve([Eq(eq, result).subs(d) for d in dict_data], unks)
eq_sol_pairs = [(eq, solvit(eq)) for eq in eqs]
DefaultDict = lambda miss_func: type("", (dict,), {"__missing__": miss_func})
DefaultEmptyDict = DefaultDict(lambda self, k: "")
msg_dict = DefaultEmptyDict({0: "No solution", 2: "Free variable"})
fmt = "# [{:^13}] {:36} -> {}"
noans = "?"
table = [(msg_dict[len(sol)], eq.subs(sol)) for eq, sol in eq_sol_pairs]
ptable = {(m, eqsol, noans if m else eqsol.subs(wanted)) for m, eqsol in table}
rows = sorted(fmt.format(*map(str, row)) for row in ptable)
for row in rows: print(row)
# Result:
# [ ] -2*A + B**2 - 9 -> 96
# [ ] -A**2/3 + 4*A*B/3 -> 96
# [ ] -A**2/3 + 4*B**2/3 - 4*B -> 96
# [ ] 2*A*B/3 + B**2/3 - 3 -> 96
# [ ] A + B**2 - 3*B -> 96
# [ ] A**2 + 4*A -> 96
# [ ] A**2 + 4*B - 12 -> 96
# [ ] A**2/3 + 2*B**2/3 - 6 -> 96
# [ ] A*B + A -> 96
# [ ] A*B + B - 3 -> 96
# [ ] B**2 - 2*B - 3 -> 96
# [ No solution ] A*B*y + B**2*z + B*x -> ?
# [ No solution ] A*y + B*z + x -> ?
# [ Free variable ] A**2*(-z + 1) + A*B*z + A*(-3*z + 4) -> ?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment