2

Is there a way to get this result without a loop? I've made a couple attempts at fancy indexing with W[range(W.shape[0]),... but have been so far unsuccessful.

import itertools
import numpy as np
n = 4
ct = 2
one_index_tuples = list(itertools.combinations(range(n), r=ct))
W = np.zeros((len(one_index_tuples), n), dtype='int')
for row_index, col_index in enumerate(one_index_tuples):
    W[row_index, col_index] = 1
print(W)

Result:

[[1 1 0 0]
 [1 0 1 0]
 [1 0 0 1]
 [0 1 1 0]
 [0 1 0 1]
 [0 0 1 1]]
1

2 Answers 2

3

You can use fancy indexing (advanced indexing) as follows:

# reshape the row index to 2d since your column index is also 2d so that the row index and 
# column index will broadcast properly
W[np.arange(len(one_index_tuples))[:, None], one_index_tuples] = 1

W
#array([[1, 1, 0, 0],
#       [1, 0, 1, 0],
#       [1, 0, 0, 1],
#       [0, 1, 1, 0],
#       [0, 1, 0, 1],
#       [0, 0, 1, 1]])
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

[[ 1 if i in x else 0 for i in range(n) ] for x in itertools.combinations( range(n), ct )]

1 Comment

this is still looping tho ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.