jennmaurice
jennmaurice

Reputation: 77

Running through combinations of 4 numbers

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

Upvotes: 3

Views: 17677

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

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']

Upvotes: 7

Raja Sattiraju
Raja Sattiraju

Reputation: 1272

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

Upvotes: 1

Related Questions