0

I am trying to select all possible sub-arrays of an array of length n which have k elements. I have just started with Python and not sure how to start with it.

I know there will be nCk (n choose k) but don't know how to start. Could anyone please give me a hint or a method I could use?

$$\frac{n!}{(n-k)!k!$$
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Gabor Bakos
  • 182
  • 1
  • 2
  • 8

2 Answers2

0

I assume you have an array of arrays - like this: [[0], [0, 0], [0]....]

All possible sub-arrays with length x would be:

def get_subarrays_of_length(in_array, length):
    out_array = []
    for item in in_array:
        if len(item) == length:
            out_array.append(item)
    return out_array

This isn't very performant, if you have a large array, you may find yourself in a pickle, but python passes objects by reference if I recall, so you should be fine - it sounds a bit like homework though.

jimf
  • 4,527
  • 1
  • 16
  • 21
0

Are you looking for itertools.combinations?

Example:

In [2]: import itertools
In [3]: a = [1,2,3,4]
In [4]: print( list(itertools.combinations( a, 2 )) )
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Sait
  • 19,045
  • 18
  • 72
  • 99