Skip to content

Instantly share code, notes, and snippets.

@fperez
Created February 13, 2011 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fperez/825317 to your computer and use it in GitHub Desktop.
Save fperez/825317 to your computer and use it in GitHub Desktop.
Permutations with repetitions
import numpy as np
def bin_perm_rep(ndim,a=0,b=1):
"""bin_perm_rep(ndim) -> ndim permutations with repetitions of (a,b).
Returns an array with all the possible permutations with repetitions of
(0,1) in ndim dimensions. The array is shaped as (2**ndim,ndim), and is
ordered with the last index changing fastest. For examble, for ndim=3:
Examples:
>>> bin_perm_rep(3)
array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]])
"""
# Create the lefttmost column as 0,0,...,1,1,...
nperms = 2**ndim
perms = np.empty((nperms,ndim),type(a))
perms.fill(a)
half_point = nperms/2
perms[half_point:,0] = b
# Fill the rest of the table by sampling the pervious column every 2 items
for j in range(1,ndim):
half_col = perms[::2,j-1]
perms[:half_point,j] = half_col
perms[half_point:,j] = half_col
return perms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment