繁体   English   中英

计算 python 中基向量和的所有排列

[英]Calculating all permuations of the sums of basis vectors in python

我试图分解一个向量,

[a,b,c]

到 [a,0,0]、[0,b,0] 和 [0,0,c],然后计算可以用这些向量创建的所有可能的总和。

例如,它应该返回

\[a,0,0\],
\[0,b,0\]
\[0,0,c\]
\[a,b,0\]
\[a,0,c\]
\[0,b,c\]
\[a,b,c\]

但对于任何长度的向量。

我试过 itertool 排列,但它似乎对这个问题不起作用。 有任何想法吗?

from itertools import combinations

# define the vector
vec = [a,b,c]

# create a list of vectors where each element of vec is set to zero
# except for one element, which is set to the corresponding value from vec
zero_vecs = [[int(i == j) * val for j, val in enumerate(vec)] for i in range(len(vec))]

# create all possible combinations of the zero_vecs list
combos = combinations(zero_vecs, r=len(vec))

# create a list of all possible sums by adding the vectors in each combination
sums = [sum(x) for x in combos]

# print the results
print("Zero vectors:")
for v in zero_vecs:
    print(v)
print("\nAll possible sums:")
for s in sums:
    print(s)

这是使用二进制逻辑执行此操作的非常简单的方法:

inp = [1, 2, 3]

result = []

for i in range(1, 2**len(inp)):
    elem = []
    for j in range(len(inp)):
        elem.append(inp[j] if ((1 << j) & i) > 0 else 0)
    result.append(elem)

print(result)

代码遍历 1 和 2**<vector length>-1 之间的所有整数,将每个 integer 视为二进制掩码。

您可以使用嵌套列表推导式在一行代码中完成同样的事情:

result = [[inp[j] if ((1 << j) & i) > 0 else 0 for j in range(len(inp))] for i in range(1, 2**len(inp))]

无论哪种情况,结果都是:

[[1, 0, 0], [0, 2, 0], [1, 2, 0], [0, 0, 3], [1, 0, 3], [0, 2, 3], [1, 2, 3]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM