Permutation with sympy I

In this notebook we’ll create all possible permutations of a 2x2 grid with 2 black and 2 white 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 2 times 1 and 2 times 0), we have to work with a function for multisets. This will remove all duplicates.

Otherwise we would have multiple times the same sequence, like

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

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

# 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

Create a list of all permutations

# Create a list with 2 zeros and 2 ones
data = [0, 0, 1, 1]

# Create all permutations of the data with sympy
permutations = multiset_permutations(data)

# Print all permutations
for p in permutations:
    print(p)
[0, 0, 1, 1]
[0, 1, 0, 1]
[0, 1, 1, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 1, 0, 0]

The function multiset_permutations() returns a generator. We could iterate on the generator itself, but for now it’s easier to convert it into a list with the function list():

# Store the result in a list
permutations = list(multiset_permutations(data))

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

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

Plot the list

# The length is 6, so we'll divide it into 2 and 3
cols = 3
rows = 2

fig = plt.figure(figsize=(cols*6, rows*6))

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_1_9_0.png