Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: TechnoCloud
Views: 149
1
def cartesian(arrays, out=None):
2
"""
3
Generate a cartesian product of input arrays.
4
Source: http://stackoverflow.com/a/1235363
5
6
Parameters
7
----------
8
arrays : list of array-like
9
1-D arrays to form the cartesian product of.
10
out : ndarray
11
Array to place the cartesian product in.
12
13
Returns
14
-------
15
out : ndarray
16
2-D array of shape (M, len(arrays)) containing cartesian products
17
formed of input arrays.
18
19
Examples
20
--------
21
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
22
array([[1, 4, 6],
23
[1, 4, 7],
24
[1, 5, 6],
25
[1, 5, 7],
26
[2, 4, 6],
27
[2, 4, 7],
28
[2, 5, 6],
29
[2, 5, 7],
30
[3, 4, 6],
31
[3, 4, 7],
32
[3, 5, 6],
33
[3, 5, 7]])
34
35
"""
36
37
arrays = [np.asarray(x) for x in arrays]
38
dtype = arrays[0].dtype
39
40
n = np.prod([x.size for x in arrays])
41
if out is None:
42
out = np.zeros([n, len(arrays)], dtype=dtype)
43
44
m = n / arrays[0].size
45
out[:,0] = np.repeat(arrays[0], m)
46
if arrays[1:]:
47
cartesian(arrays[1:], out=out[0:m,1:])
48
for j in xrange(1, arrays[0].size):
49
out[j*m:(j+1)*m,1:] = out[0:m,1:]
50
return out
51