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']
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
JapexDoe
  • 55
  • 3
  • 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. – Eli Korvigo Dec 07 '17 at 15:03

4 Answers4

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']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Awesome answer, what if I had multiple operands? – JapexDoe Dec 07 '17 at 15:20
  • @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? – Ajax1234 Dec 07 '17 at 15:24
  • 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 Dec 07 '17 at 15:37
  • @JapexDoe please see my recent edit. – Ajax1234 Dec 07 '17 at 16:07
  • Thanks! Your Awesome! :) – JapexDoe Dec 07 '17 at 17:14
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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Use itertools.permutations:

from itertools import permutations

input = [3, 8, 2]
output = map('-'.join, permutations(map(str, input), 2))
user2390182
  • 72,016
  • 6
  • 67
  • 89
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)
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88