如何用Python生成满足按位与和闭包的最大二进制向量空间
向量空间分组需求与现有方案问题
给定样本数组:
[[1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]
需要生成所有满足以下条件的最大向量空间:
- 空间对按位与的和操作封闭
- 空间内任意两个向量按位与后的元素和≥用户指定的常数
举个例子:上述数组可以生成3个符合要求的向量空间V1、V2、V3。
已尝试的两种方案及存在的问题
1. 正则表达式方法
代码如下:
def match_strings(strings, pattern, indices): matched_strings = [(idx, string) for idx, string in zip(indices, strings) if re.match(pattern, string)] return matched_strings def identify_user_distribution(availability_matrix, indices): string_rep = [] for instance in availability_matrix: temp = '' for item in instance: temp += str(item) string_rep.append(temp) patterns = set(string_rep) patterns = [instance.replace('0', "[01]+") for instance in patterns] clusters = [] for instance_pattern in patterns: cluster = match_strings(string_rep, instance_pattern, indices) clusters.append([cluster[0][0], cluster[-1][0]]) return clusters
问题:该方法无法保证闭包性,会混入不符合条件的向量。
2. NumPy方法
代码如下:
def bitwise_and_groups_with_sum(vectors, target_sum): groups = {} index = {} flag = False for idx, vector in enumerate(vectors): temp = '' for item in vector: temp += str(item) if len(groups) == 0: groups[temp] = [vector] index[temp] = [idx] else: for key, value in groups.items(): if vector in value: index[key].append(idx) continue elif np.all([np.bitwise_and(vector, instance).sum() == target_sum for instance in value]): groups[key].append(vector) index[key].append(idx) flag = True if not flag: groups[temp] = [vector] index[temp] = [idx] flag = False return index
问题:无法正确实现闭包逻辑。
求助
希望得到高效的解决方案建议,能够正确生成符合要求的所有最大向量空间。
内容的提问来源于stack exchange,提问作者Gopal Bhattrai
相关产品推荐
相关产品推荐

