Cells (Armin Hofmann) with sympy I

Cells (Armin Hofmann) with sympy I

Task: Use sympy to create a program that outputs all possibilities of a 3 x 3 grid, containing 3 white cells (zeros) and 6 black cells (ones). (So it’s a little simplification of the image above, which contains also symbols with 2 or 4 white cells.)

Imports

from sympy.utilities.iterables import multiset_permutations
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
import math

Create a list of all permutations

ones = np.ones(6, dtype=np.int8)  # Create an array of 1s
zeros = np.zeros(3, dtype=np.int8)  # Create an array of 0s
data = np.concatenate((ones, zeros))  # Combine the arrays
print(data)  # Check the data
[1 1 1 1 1 1 0 0 0]
# Create all permutations and store them in a list
permutations = list(multiset_permutations(data))
# Print the length
print(len(permutations))
# Print the first items
for p in permutations[:5]:
    print(p)
84
[0, 0, 0, 1, 1, 1, 1, 1, 1]
[0, 0, 1, 0, 1, 1, 1, 1, 1]
[0, 0, 1, 1, 0, 1, 1, 1, 1]
[0, 0, 1, 1, 1, 0, 1, 1, 1]
[0, 0, 1, 1, 1, 1, 0, 1, 1]
columns = 7
rows = 12
fig=plt.figure(figsize=(columns*3, rows*3))
cmap = colors.ListedColormap(['white','black'])

for index, value in enumerate(permutations):
    # Resshape the data into a grid
    data = np.array(value).reshape((3, 3))
    
    # Add a subplot
    fig.add_subplot(rows, columns, index+1)
    # exclude ticks
    plt.xticks(ticks=[])
    plt.yticks(ticks=[])
    plt.imshow(data, cmap=cmap)
    
# Show the whole plot
plt.show()
_images/cells_sympy_1_8_0.png

Now we have plotted all possibilities of a 3x3 grid with 3 white and 6 black cells. Next we’ll reduce this list based on a condition like a black cell in the center. Beforehand we’ll learn conditions.