简体   繁体   English

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

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

I'm trying to break down a vector,我试图分解一个向量,

[a,b,c] [a,b,c]

into [a,0,0], [0,b,0] and [0,0,c] and then calculate all possible sums that can be created with these vectors.到 [a,0,0]、[0,b,0] 和 [0,0,c],然后计算可以用这些向量创建的所有可能的总和。

For example, it should return例如,它应该返回

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

but for any length vector.但对于任何长度的向量。

Ive tried itertool permutations, but it doesnt seem to work for this problem.我试过 itertool 排列,但它似乎对这个问题不起作用。 Any ideas?有任何想法吗?

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)

Here's a very simple way to do this using binary logic:这是使用二进制逻辑执行此操作的非常简单的方法:

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)

The code iterates through all of the integers between 1 and 2**<vector length>-1, treating each integer as a binary mask.代码遍历 1 和 2**<vector length>-1 之间的所有整数,将每个 integer 视为二进制掩码。

You can do the same thing in a single line of code with nested list comprehensions:您可以使用嵌套列表推导式在一行代码中完成同样的事情:

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

In either case, the result is:无论哪种情况,结果都是:

[[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