簡體   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