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 that the values ​​would be integer and positive, and did the following:

  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 expand the range to a = range(-100,100) . After solving the equation manually (using Google), I know that float are involved, for example. A = 3.5 etc.

But then how to solve the problem with Python.

+5
source share
2 answers

There is no need to study matrix theory (at least not for this).

 >>> from sympy import * >>> var('ABC D') (A, B, C, D) >>> solve([A+B-8,B+D-8,A+C-13,CD-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 part '= 0'.

+6
source

If you know linear algebra, you can ask a question as a system of equations, which is then trivial to solve using a freely available and popular library called numpy (tip 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 to update matrix math / linear algebra behind this python solution, you can check https://www.mathsisfun.com/algebra/systems-linear-equations-matrices.html .

+8
source

Source: https://habr.com/ru/post/1261463/


All Articles