This is a fun exercise that tries to answer the following question: if the elements from a square matrix are randomly chosen from 0 to 9, is it more like that the determinant would be even or odd?
I'm pretty sure there are different ways of optimizing this piece of code. The first one that comes to my mind is to use only generators (maybe?) and not use the for loop to fill values.
import itertools import math import matplotlib.pyplot as plt import numpy as np n = 4 lst = list(itertools.product([0, 1], repeat=n)) algo = list(itertools.product(lst, repeat=n)) determinants = np.abs(np.linalg.det(algo)) determinants = np.where(determinants % 2 == 0, 0, 1) square = math.ceil((math.sqrt(len(determinants)))) ** 2 # fill with generic value if not a perfect square for num in range(square - len(determinants)): determinants = np.append(determinants, -1) matrix = np.reshape(determinants, (int(math.sqrt(square)), int(math.sqrt(square)))) fig, ax = plt.subplots() # or ax.imshow(matrix, cmap="Greens") plt.show()
All suggestions are welcome :D