How to generate these vectors quickly in Python? -


suppose want generate vectors of length n such k components of n positions +1 or -1 (there no restrictions on being +1 or -1), , remaining n-k components zero.

i can write code follows:

from itertools import combinations, product result = []     x in combinations(range(n),k):     y in product([-1,1],repeat=k)         0 = [0] * n         in x:             b in y:                 zero[a] = b                 result.append(zero) 

this way works, think bit tedious. there fast way give result?

let's write function generates vectors of length n k 1s , n - k 0s:

def gen(n, k):     indices in itertools.combinations(range(n), k):         l = [0] * n         in indices:             l[i] = 1         yield(l) 

then, let's turn of 1s -1s:

def gen(n, k):     indices in itertools.combinations(range(n), k):         # each 1 of indices can -1 or +1         in range(len(indices) + 1):             neg_indices in itertools.combinations(indices, i):                 l = [0] * n                 in indices:                     l[i] = 1                 in neg_indices:                     l[i] = -1                 yield(l) 

sample output:

>>> list(gen(3, 2)) [[1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]] 

your original implementation close; fix it:

def gen(n, k):     x in itertools.combinations(range(n), k):         y in itertools.product([-1,1], repeat=k):             0 = [0] * n             a, b in zip(x, y):                 zero[a] = b             yield 0 

note use of zip instead of nesting.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -