#!/usr/local/cpython-3.8/bin/python3 """Use linear algebra to solve a particular math problem GG gave me.""" import numpy # The original problem was: # green + blue = yellow # red + green = purple # red + purple = yellow # red + green + blue = 9 # # solve for yellow def try_solve(): """Try numpy.linalg.solve - this method fails.""" # y g b r p nested_list = [ [-1, 1, 1, 0, 0], [0, 1, 0, 1, -1], [-1, 0, 0, 1, 1], [0, 1, 1, 1, 0], ] # print(nested_list) a = numpy.array(nested_list) # print(A) b = numpy.array([0, 0, 0, 9]) # print(b) # This gives: numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square x = numpy.linalg.solve(a, b) print(x) def try_semimanual(): """Try to do it a row at a time, using numpy for the row-by-row computations.""" # y g b r p = nested_list = [ [-1.0, 1.0, 1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0, -1.0, 0.0], [-1.0, 0.0, 0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0, 0.0, 9.0], ] a = numpy.array(nested_list) print(a) print() # This prints a row vector # print(a[1, ]) a[0, ] *= -1.0 a[2, ] += a[0, ] a[2, ] += a[1, ] a[3, ] -= a[1, ] a[2, ] *= -1.0 a[3, ] -= a[2, ] a[3, ] /= 2.0 a[0, ] += a[1, ] a[0, ] += a[2, ] a[0, ] += a[3, ] print(a) # Alden and GG's sister say they were able to come up with a single value for y, but I get: # y g b r p = # [ 1. 0. 0. 0. -0.5 4.5] # y - 0.5p = 4.5 # y = 0.5p + 4.5 # So plugging in p = 1, y = 0.5 + 4.5 I get: # purple = 1, yellow = 5 # green + blue = 5 # red + green = 1 # red + 1 = 5 # red + green + blue = 9 # Plugging in red = 4: # green + blue = 5 # 4 + green = 1 # 4 + 1 = 5 # 4 + green + blue = 9 # Which means: # green + blue = 5 # green = -3 # which means: # -3 + blue = 5 # So blue is 8. # So if purple = 1, then: # yellow = 5 # red = 4 # green = -3 # blue = 8 # so checking that: # -3 + 8 = 5 # 4 + -3 = 1 # 4 + 1 = 5 # 4 + -3 + 8 = 9 # Which isn't an incorrect set of equations, so I suspect my solution is correct: # yellow = 0.5*purple + 4.5 def main(): """Invoke the preferred solution.""" try: # this fails, because the matrix isn't square try_solve() except numpy.linalg.LinAlgError: pass try_semimanual() main()