-1

I do this:

from itertools import chain, combinations, permutations
import itertools

i = [5, 6, 7]

x = list(combinations(i, 2))

x.append((x[1][0],))

x = list(itertools.chain.from_iterable(x))

to take all the possible permutations but in a flattened list where each pair of adjacent elements corresponds to a permutation.

This gives:

[5, 6, 5, 7, 6, 7, 5]

where the pairs of adjacent elements in this list are all the permutations:

(5,6), (6,5), (5,7), (7,6), (6,7), (7,5) 

instead of the classic list of tuples with permutations:

[(5, 6), (5, 7), (6, 5), (6, 7), (7, 5), (7, 6)]

Is there any function or way which does this in a more concise and/or quick way than my code?

Outcast
  • 4,967
  • 5
  • 44
  • 99
  • 2
    why the output of your code only have 4 pairs instead of 6 as in the classic? – Quang Hoang Nov 26 '19 at 17:21
  • I'm not clear on what you want. You state that you want only adjacent elements, but your code finds all permutations. – Prune Nov 26 '19 at 17:21
  • The code generates all combinations, then adds a reversed copy involving the end elements. – Prune Nov 26 '19 at 17:22
  • @QuangHoang, if you take all the pairs of adjacent elements then they are 6 ;) and actually the correspond to all permutations. Is is clearer now? – Outcast Nov 26 '19 at 18:00
  • @Prune, I want all permutations but in a flattened list where each pair of adjacent elements correponds to one permutation. – Outcast Nov 26 '19 at 18:01
  • @QuangHoang, the list which I generated is `[5, 6, 5, 7, 6, 7, 5]` and the pairs of adjacent elements in this list are: `(5,6), (6,5), (5,7), (7,6), (6,7), (7,5)` which are all the permutations, right? ;) – Outcast Nov 26 '19 at 18:05
  • As far as I can think of, your code works pretty well and concise. Although, `x.append((x[1][0],))` can be replaced by `x.append((i[0],))` so it can work with list of 2 elements. – Quang Hoang Nov 26 '19 at 18:06
  • @QuangHoang, ok if my code is ok then it is fine. I thought that there would a function or something that I did not know which was doing this even better. – Outcast Nov 26 '19 at 18:08

1 Answers1

0

You are calling a combination function instead of permutation. Try this

from itertools import chain, combinations, permutations
import itertools

i = [5, 6, 7]

x = list(permutations(i, 2))
print(x)
Yugesha Sapte
  • 105
  • 1
  • 1
  • 9