Pairwise Crossproduct in Python

Pairwise crossproduct in Python

You're looking for itertools.product if you're on (at least) Python 2.6.

>>> import itertools
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> itertools.product(a,b)
<itertools.product object at 0x10049b870>
>>> list(itertools.product(a,b))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

How to get the cartesian product of a series of lists

Use itertools.product, which has been available since Python 2.6.

import itertools

somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
for element in itertools.product(*somelists):
print(element)

This is the same as:

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
print(element)

All pairwise cross products of the rows of two matrices

Looks like cross broadcasts the leading dimensions.

np.cross(A[:, None,:], B[None, :,:])

cross product in python of arbitrarily many lists

You are looking for itertools.product:

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example,
product(A, B) returns the same as ((x,y) for x in A for y in B).

The nested loops cycle like an odometer with the rightmost element
advancing on every iteration. This pattern creates a lexicographic
ordering so that if the input’s iterables are sorted, the product
tuples are emitted in sorted order.

To compute the product of an iterable with itself, specify the number
of repetitions with the optional repeat keyword argument. For example,
product(A, repeat=4) means the same as product(A, A, A, A).

So you just need to do

itertools.product(L, repeat=n)

How to get a cartesian-product of all pair from two vectors in numpy?

From a simpler understanding point of view, an assignment based would make sense. Hence -

dt = np.result_type(A.dtype,B.dtype)
s = A.shape
C = np.empty((s[0],)+(2,)+s[1:],dtype=dt)
C[:,0] = A
C[:,1] = B

This could be simplified with a stacking operation for a one-liner -

C = np.stack((A,B),axis=1)

Bit of explanation on how these two methods solve it :

The one-liner is basically stacking A after B. In the first approach, the resultant is a 2 element ndarray along the second axis - s[0],)+(2,)+s[1:]. Thus, each element off A and off B are interleaved along that axis. This stacking operation has a NumPy builtin np.stack, which is the second method. Hence, these two are equivalent and solve our case.

And some verification :

Question is asking for - a new matrix C, in which every element (C[i]) is a matrix of shape (2, 3, 4, 5). Hence, C would be of shape (n,2,3,4,5). The stacking is along the second axis. Furthermore, from what I have understood, the question is asking for C[k][0] == A[k] for k=0..n and C[k][1] == B[k] for k=0..n. Let's prove that -

In [323]: n = 1000
...: A = np.random.rand(n, 3, 4, 5)
...: B = np.random.rand(n, 3, 4, 5)

In [324]: C = np.stack((A,B),axis=1)

In [325]: np.all([np.allclose(C[i][0],A[i]) for i in range(1000)])
Out[325]: True

In [326]: np.all([np.allclose(C[i][1],B[i]) for i in range(1000)])
Out[326]: True

How can I do cross multiplication with strings in Python?

Three options in vanilla Python that come to mind. For all these options, you really don't need to prepend ' of ' to the suit name. I will work with the implication that CardTypes = ['Hearts', 'Spades', 'Diamonds', 'Clubs'].

  1. Use a nested for loop. After all, that's what a cross product is:

    deck = []
    for rank in Deck13Sample:
    for suit in CardTypes:
    deck.append(f'{rank} of {suit}')
  2. The same thing can be expressed much more concisely as a list comprehension. This is the option I would recommend:

    deck = [f'{rank} of {suit}' for rank in Deck13Sample for suit in CardTypes]

    Notice that the order of the loops is the same as in #1.

  3. Finally, if you want to use a fancy library import (but one that comes with Python), you can use itertools.product, which is basically an indefinitely nested set of for loops, and therefore overkill for this problem:

    deck = [f'{rank} of {suit}' for rank, suit in itertools.product(Deck13Sample, CardTypes)]

For reference, the numbers are called "rank" and the symbols are called "suit" on a deck of cards.

Efficient way of computing the cross products between two sets of vectors numpy

Like many numpy functions cross supports broadcasting, therefore you can simply do:

np.cross(tangents_x[:, None, :], tangents_y)

or - more verbose but maybe easier to read

np.cross(tangents_x[:, None, :], tangents_y[None, :, :])

This reshapes tangents_x and tangents_y to shapes 2000, 1, 3 and 1, 2000, 3. By the rules of broadcasting this will be interpreted like two arrays of shape 2000, 2000, 3 where tangents_x is repeated along axis 1 and tangents_y is repeated along axis 0.

Permutation of two lists

This should do what you're looking for:

>>> ["/".join(x) for x in itertools.product(first, second)]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>>

You can also do it without itertools:

>>> [x + "/" + y for x in first for y in second]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>>


Related Topics



Leave a reply



Submit