Permutation with sympy II

In this notebook we’ll create all possible permutations of a 2x2 grid, with all combinations from 4 white to 4 black cells

We’ll use the library sympy for that.

https://docs.sympy.org

https://docs.sympy.org/latest/modules/combinatorics/permutations.html

When we’re working with data where multiple values are equal (like 4 times 1 and 4 times 0), we have to work with a function for multisets. This will remove all duplicates.

Otherwise we would have every version multiple times, like

[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

where each number is a different item of the list, but the result is the same.

Furthermore we have to reduce the length of the returned sequence to 4 items. Otherwise multiset_permutations() will return all permutations of a sequence of 8 items (4 white + 4 black).

# Run this cell to install sympy
!pip install sympy

Imports

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

Create a list of all permutations

# Create a numpy array with 4 zeros and 4 ones

# First create an empty list
data = []

# Now we'll use a for loop with 4 iterations (for 4 cells)
for i in range(4):
    # Add a 0
    data.append(0)
    # Add a 1
    data.append(1)
    
# Check the data
print(data)

# Print all permutations
# We'll insert a second argument size=4 to the function
# multiset_permutations to receive all permutations of length 4
for p in multiset_permutations(data, size=4):
    print(p)
[0, 1, 0, 1, 0, 1, 0, 1]
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[0, 1, 1, 1]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 0, 1, 1]
[1, 1, 0, 0]
[1, 1, 0, 1]
[1, 1, 1, 0]
[1, 1, 1, 1]
# Store the result in a list
permutations = list(multiset_permutations(data, size=4))

# Print the first item
print(permutations[0])

# Print the length of the list
print(len(permutations))
[0, 0, 0, 0]
16

Plot the list

# The length is 16, so we'll divide it into 4 and 4
cols = 4
rows = 4

fig = plt.figure(figsize=(cols*4, rows*4))
cmap = ListedColormap(['white', 'black'])

for index, values in enumerate(permutations):
    # Reshape the data into a 2 x 2 grid
    data = np.array(values).reshape((2,2))
    
    # Set a title
    title = str(data)
    
    # Add the plot to the larger plot
    fig.add_subplot(rows, cols, index+1).set_title(title)
    plt.xticks(ticks=[])
    plt.yticks(ticks=[])
    plt.imshow(data, cmap=cmap)

# Display the plot
plt.show()
_images/permutations_sympy_2_8_0.png