我正在尝试修改 Hilberts 在下面的问题中作为答案提供的代码,以允许它用于多个 values 而不仅仅是二进制。 https://stackoverflow.com/questions/71654582/all-binary-combinations-in-a-2d-numpy
因此,我不想像前面的例子那样只允许 0 和 1 ,而是希望找到所有 combinations 没有旋转的数据,比如 0, 1, 2 和 3 。
我是这样修改的,主要是把原代码中的“2”换成一个变量,并尝试用变量“m”来代替,以遵循最初的公式。但我认为这里的问题与 numpy 类型的数据“bitwise_and”有关。有没有人对会出现什么问题或任何提示有任何建议?
def get_binary_mats(n,m):
# all possible n by n binary matrices up to rotation:
bin_mats = (np.bitwise_and(np.arange(m**(n*n))[:,None], m ** np.arange(n*n)) > 0)\
.reshape(-1, n, n)
# define a score for each matrix based on position of ones
score = m ** np.arange(n*n).reshape(n,n)
# array([[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]])
score_arr = np.stack([np.rot90(score, k=k) for k in range(4)])
# array([[[ 1, 2, 4],
# [ 8, 16, 32],
# [ 64, 128, 256]],
# [[ 4, 32, 256],
# [ 2, 16, 128],
# [ 1, 8, 64]],
# [[256, 128, 64],
# [ 32, 16, 8],
# [ 4, 2, 1]],
# [[ 64, 8, 1],
# [128, 16, 2],
# [256, 32, 4]]])
scores = np.einsum("ijk,ljk->il", bin_mats, score_arr)
_, idx = np.unique(scores.min(1), return_index=True)
return bin_mats[idx,...]
谢谢
回答1
from itertools import combinations_with_replacement as combn
list(combn([0,1,2,3], 4))
[(0, 0, 0, 0),
(0, 0, 0, 1),
(0, 0, 0, 2),
(0, 0, 0, 3),
(0, 0, 1, 1),
(0, 0, 1, 2),
(0, 0, 1, 3),
(0, 0, 2, 2),
(0, 0, 2, 3),
(0, 0, 3, 3),
(0, 1, 1, 1),
(0, 1, 1, 2),
(0, 1, 1, 3),
(0, 1, 2, 2),
(0, 1, 2, 3),
(0, 1, 3, 3),
(0, 2, 2, 2),
(0, 2, 2, 3),
(0, 2, 3, 3),
(0, 3, 3, 3),
(1, 1, 1, 1),
(1, 1, 1, 2),
(1, 1, 1, 3),
(1, 1, 2, 2),
(1, 1, 2, 3),
(1, 1, 3, 3),
(1, 2, 2, 2),
(1, 2, 2, 3),
(1, 2, 3, 3),
(1, 3, 3, 3),
(2, 2, 2, 2),
(2, 2, 2, 3),
(2, 2, 3, 3),
(2, 3, 3, 3),
(3, 3, 3, 3)]