3

I need a code that would run through the possible combinations of 4 numbers e.g 1234 would produce 24 combinations of 1234, 1243, 1324 ... ect ect. But does not do ['1', '12', '123', ect] I want it to be only 4 number length combinations, (just changing the order)
A long option would be to

    import random

randomise one of the 4 numbers, randomise another and another and another, check if that combination had been printed or like added to an array that held the possible combinations and then eventually printed out all of them.

array = ['1234', '1243', '1342', '1324' ect]


That would take long though and is highly inefficient. Pretty new to coding :) Thanks

Shawn
  • 47,241
  • 3
  • 26
  • 60
jennmaurice
  • 77
  • 1
  • 1
  • 8
  • maybe this question could help: http://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements – boroboris Apr 26 '17 at 09:36
  • @boroboris I don't want it to be '1' '12' '123' which would produce more than 24 combinations. Will add this to the description. Thank you for the suggestion though – jennmaurice Apr 26 '17 at 09:37
  • @Mormin Hi Im pretty new to this. Can you explain what is wrong with my question? Thanks – jennmaurice Apr 26 '17 at 12:05

2 Answers2

7

The solution using itertools.permutations() and str.join() functions:

import itertools

n = '1234'
a = [''.join(i) for i in itertools.permutations(n, 4)]

print(a)   # prints 24 permutations

The output:

['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

You can use the builtin module itertools in python. Refer to this question already asked here

import itertools
array = itertools.permutations([1, 2, 3, 4])

for eachpermutation in array:
    print(eachpermutation )

Should give you the output such as this

(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)

If you need to concatenate the sublists into a single number, you can use the answer provided here

for eachpermutation in array:
    print(int(''.join(str(i) for i in eachpermutation )))

gives you the following output

1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

Hope that helps

Community
  • 1
  • 1
Raja Sattiraju
  • 1,262
  • 1
  • 20
  • 42