Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve this math puzzle with Python?

   A + B = 8
   B + D = 8
   A + C = 13
   C - D = 6

How to find the values of A, B, C and D?

I assumed the values would be integers and positive and did this:

   a = range(0,14)
   b = c = d = a
   for i in a:
     for x in b:
      for y in c:
        for z in d:
          if (a[i] + b[x] == 8 and a[i] + c[y] == 13 and b[x] + d[z] == 8 and c[y]-d[z]==6):
            print(a[i],b[x],c[y],d[z])

But that does not work. Even then I extend range to a = range(-100,100). After solving the equation by hand (with Google's help) I know that floats are involved, e.g. A = 3.5 etc.

But then how to solve it with Python.

like image 346
Wlad Avatar asked Dec 18 '16 17:12

Wlad


2 Answers

If you know linear algebra, you can frame the question as a system of equations, which is then trivial to solve using a freely-available and popular library called numpy (hat tip @Griboullis):

import numpy as np

A = [[1, 1, 0, 0], 
     [0, 1, 0, 1], 
     [1, 0, 1, 0], 
     [0, 0, 1, -1]]
b = [8, 8, 13, 6]
answer = np.linalg.solve(A, b)

If you want a refresher at the matrix math/linear algebra behind this python solution, you can check out https://www.mathsisfun.com/algebra/systems-linear-equations-matrices.html.

like image 141
finbarr Avatar answered Sep 30 '22 08:09

finbarr


There's no need to learn matrix theory (at least not for this).

>>> from sympy import *
>>> var('A  B C D')
(A, B, C, D)
>>> solve([A+B-8,B+D-8,A+C-13,C-D-6])
{B: 9/2, D: 7/2, C: 19/2, A: 7/2}

You just need to express each equation such as A+B=8 in the form A+B-8=0 and then omit the '=0' part.

like image 20
Bill Bell Avatar answered Sep 30 '22 09:09

Bill Bell