Solved: how to pairwise permute in python

The main problem with pairingwise permutation in Python is that it is not efficient.


I have a list of integers, and I want to pairwise permute them in all possible ways. For example, if the input is [1,2,3], the output should be [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]].
How can I do this in Python?


A:

You can use <code>itertools.permutations</code>:
<code>&gt;&gt;&gt; from itertools import permutations
&gt;&gt;&gt; list(permutations([1, 2], 2))  # for your example input [1, 2]
[(1, 2), (2, 1)]  # output is a generator object which you can convert to a list as shown above. 
</code>

If you want to do it for all possible inputs, you can use a list comprehension:
>>> from itertools import permutations
>>> [list(permutations([1, 2, 3], 2))] # for your example input [1, 2]
[[(1, 2), (2, 1)], [(1, 3), (3, 1)], [(2, 3), (3, 2)]] # output is a list of generator objects which you can convert to lists as shown above.

Pairwise combinations of a list

In Python, you can combine two lists using the + operator. The first list is the “left operand” and the second list is the “right operand”.

For example, to create a list of pairs consisting of the first letter of each word in a text file, you could use the following code:

text_file = open(“my_text_file.txt”) words = text_file.read().split(” “) print(“Pairwise combinations of words in text file:”) for word in words: if word not in [“a”, “an”, “the”, “of”]: print(word + “, ” + str(pairs[word]))

Vectorizing pirwise combinations

In Python, you can vectorize combinations of pirwise operators by using the vectorized() function. This function takes a list of tuples and returns a list of vectors. Each vector in the returned list represents a single combination of the pirwise operators.

For example, the following code snippet uses the vectorized() function to create a list of vectors representing all possible combinations of + and – operations:

vectorized = [] for i in range(1, 10): vectorized.append(vectorized[i] + vectorized[i – 1])

Related posts:

Leave a Comment