2

How do I generate all possible pairs permutations from a list in Python?

Example:

input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
1
  • Welcome to SO. This is not a free code-writing service, hence your question is supposed to present your own attempts. Moreover, this question is a duplicate. Commented Dec 7, 2017 at 15:03

4 Answers 4

4

You can use itertools.permutations:

import itertools
input = [3, 8, 2]
final_list = ["{}-{}".format(*i) for i in itertools.permutations(input, 2)]

Output:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

However, if you want all operations up-to and including the length of the list, you can try this:

final_list = list(itertools.chain(*[['-'.join(["{}"]*b).format(*i) for i in itertools.permutations(input, b)] for b in range(2, len(input)+1)]))

Output:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8', '3-8-2', '3-2-8', '8-3-2', '8-2-3', '2-3-8', '2-8-3']

Edit: for all possible operands:

import re
def tokenize(s):
   converter = {"-":lambda x, y:x-y, '+':lambda x, y:x+y}
   total = 0
   stack = re.findall('\d+|[\-\+]', s)
   operator = None
   for i in stack:
      if i.isdigit():
         if not operator:
            total += int(i)
         else:
            total = converter[operator](total, int(i))
            operator = None
      else:
          operator = i
   return total

new_list = set(list(itertools.chain(*list(itertools.chain(*[[[''.join([''.join('{}'+i) for i in b]+['{}']).format(*c) for b in itertools.permutations(['-', '+'], len(c)-1)] for c in itertools.permutations(input, x)] for x in range(2, len(input)+1)])))))
final_list = {tokenize(a):a for a in new_list}
new_final_list = [b for a, b in final_list.items()]

Output:

['3-2', '8-3', '8-2', '8-3+2', '8-2+3', '8+2', '8+3', '2-8', '3-8', '3+2-8', '2-3']
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome answer, what if I had multiple operands?
@JapexDoe glad to help! Regarding multiple operands, this answer will find all possible operations given a list. Do you mean an input of multiple lists, with the goal to find the operations for every one of those lists?
I'm new to Python, trying to understand some of the more advanced problems. What I meant is that if I need to find both plus and minus operands with the given problem. Also: Is there a way to reduce the list down to remove all elements that yield the same outcome? (2+8 and 8+2 are both 10). Or by not using permutations? No need to spend too much time on this for me, I can probably figure something out on my own :)
@JapexDoe please see my recent edit.
Thanks! Your Awesome! :)
3

just feed your list to itertools.permutations and format accordingly in a list comprehension directly passing the tuple to format using the * operator.

import itertools

result = ["{}-{}".format(*x) for x in itertools.permutations([3, 8, 2],2)]

print(result)

result:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

As a side note, don't use input as a variable name as it overrides the interactive text input function.

Comments

0

Use itertools.permutations:

from itertools import permutations

input = [3, 8, 2]
output = map('-'.join, permutations(map(str, input), 2))

Comments

0

You can try itertools:

Data is:

input = [3, 8, 2]
import itertools

One line solution:

print(['{}-{}'.format(i[0],i[1]) for i in itertools.permutations(input,r=2)])

Detailed solution:

Above list comprehension is same as:

final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append(('{}-{}'.format(i[0],i[1])))
print(final_list)

If you want the result of subtraction then:

final_list=[]
for i in itertools.permutations(input,r=2):
    final_list.append((i[0]-i[1]))
print(final_list)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.