-6

first of all I would like to inform you I don't have any knowledge about python. I tryed to figure the basics by searching trough some beginner tutorials but I can't even wrap my head around those.

As I have a very specific thing I'd like to generate I hope theres someone over here who could help me out.

I need all the possible combinations between the numbers 1,2,3,4,5,6,7,8 the first and the last number always have to be 1 and the numbers can't be used twice.

for example:

1 2 3 4 5 6 7 8 1 -
1 2 3 4 5 6 8 7 1 -
1 2 3 4 5 7 8 6 1 - 
1 2 3 4 5 7 6 8 1 -
1 2 3 4 5 8 6 7 1 - 
1 2 3 4 5 8 7 6 1 -

and so on :)

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Welcome to SO, as you may know SO is not a coder writing service! So pls give a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) about what you want to do?or the code that you have tried so far? – Mazdak Jul 02 '15 at 07:35
  • also you didn't specify how long your sequences must be – Marcus Müller Jul 02 '15 at 07:36
  • `import itertools itertools.permutations([1,2,3])` – sinhayash Jul 02 '15 at 07:36
  • If they are always 9 numbers long, but always start with 1 and end with one, and you can't use 1 inside the "inner" 7 numbers, it's the problem of finding all permutations of 7 numbers in 7 places. It's well known that this has 7! permutations, 5040. – Marcus Müller Jul 02 '15 at 07:39

2 Answers2

1

You want the permutations of the numbers 2 through to 8, and then just add the 1's:

from itertools import permutations

for combo in permutations(range(2, 9)):
    combo = (1,) + combo + (1,)
    print(combo)

Demo:

>>> from itertools import permutations
>>> for combo in permutations(range(2, 9)):
...     combo = (1,) + combo + (1,)
...     print(combo)
... 
(1, 2, 3, 4, 5, 6, 7, 8, 1)
(1, 2, 3, 4, 5, 6, 8, 7, 1)
(1, 2, 3, 4, 5, 7, 6, 8, 1)
(1, 2, 3, 4, 5, 7, 8, 6, 1)
(1, 2, 3, 4, 5, 8, 6, 7, 1)
(1, 2, 3, 4, 5, 8, 7, 6, 1)
(1, 2, 3, 4, 6, 5, 7, 8, 1)
(1, 2, 3, 4, 6, 5, 8, 7, 1)
(1, 2, 3, 4, 6, 7, 5, 8, 1)
#
# ... many lines omitted
#
(1, 8, 7, 6, 4, 3, 2, 5, 1)
(1, 8, 7, 6, 4, 3, 5, 2, 1)
(1, 8, 7, 6, 4, 5, 2, 3, 1)
(1, 8, 7, 6, 4, 5, 3, 2, 1)
(1, 8, 7, 6, 5, 2, 3, 4, 1)
(1, 8, 7, 6, 5, 2, 4, 3, 1)
(1, 8, 7, 6, 5, 3, 2, 4, 1)
(1, 8, 7, 6, 5, 3, 4, 2, 1)
(1, 8, 7, 6, 5, 4, 2, 3, 1)
(1, 8, 7, 6, 5, 4, 3, 2, 1)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
from itertools import permutations

for a in permutations(range(2, 9)):
    a = (1,) + a + (1,)
    print(a)

For learning more try this: how-to-generate-all-permutations-of-a-list-in-python

Community
  • 1
  • 1
sinhayash
  • 2,693
  • 4
  • 19
  • 51