1

I need help creating a program in python that shows you all the possible combinations. For example: i give it numbers "1 2 3" and i gives me "1 3 2", "3 2 1", "3 1 2", "2 1 3", "2 3 1".

user2458048
  • 116
  • 1
  • 4
  • 13

2 Answers2

4

Use itertools. It makes life easy for this:

import itertools

perms = itertools.permutations([1,2,3])

for perm in perms:
    print perm

>>>(1, 2, 3)
>>>(1, 3, 2)
>>>(2, 1, 3)
>>>(2, 3, 1)
>>>(3, 1, 2)
>>>(3, 2, 1)
That1Guy
  • 7,075
  • 4
  • 47
  • 59
  • is there a way to enter the numbers i get from the script and put them into a password protected .py? for example i run pass.py and it ask me for a password then i run the combonation script and it enters all the possible combonation of numbers i give it into the pass.py? or something similar – user2458048 Jun 06 '13 at 21:37
  • I would recommend asking another question, for that one. – That1Guy Jun 06 '13 at 21:43
  • actually both if you can help me? – user2458048 Jun 06 '13 at 21:44
  • Look into using `sys.argv[1]` – That1Guy Jun 06 '13 at 21:45
  • Also, if this answers your original question, you should mark it as correct to help anybody else that might see this page in the future. – That1Guy Jun 06 '13 at 21:48
0
from itertools import combinations as c
for x in c([1, 2, 3],2): print x
(1, 2)
(1, 3)
(2, 3)
print [x for x in c(range(5), 3)]                                        
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
alinsoar
  • 15,386
  • 4
  • 57
  • 74