How to generate python combinations of 4 digits in list of various digits?

72
February 12, 2019, at 11:20 PM

I have a list such as

x=[1,2,4,5,8,9]

What I wanted to implement is to get a list which contains combination of 4 digits out of the list. For example: Output should be

[1,2,4,5]
[2,3,4,8]
.....
[1,3,5,8]
....

Hence, I believe it will be 4^6 solutions. I have tried itertools combination with no success

Answer 1

Itertools is actually the answer, because what you want are permutations of length N.

import itertools as it
x=[1,2,4,5,8,9]
print(list(it.permutations(x, 4)))
Answer 2

If order does not matter you should use itertools.combinations:

from itertools import combinations
x=[1,2,4,5,8,9]
for c in combinations(x, 4):
    print(c)

This outputs:

(1, 2, 4, 5)
(1, 2, 4, 8)
(1, 2, 4, 9)
(1, 2, 5, 8)
(1, 2, 5, 9)
(1, 2, 8, 9)
(1, 4, 5, 8)
(1, 4, 5, 9)
(1, 4, 8, 9)
(1, 5, 8, 9)
(2, 4, 5, 8)
(2, 4, 5, 9)
(2, 4, 8, 9)
(2, 5, 8, 9)
(4, 5, 8, 9)
Answer 3

You can try this:

from itertools import combinations
x=[1,2,4,5,8,9]
comb = list(map(list, itertools.combinations(x, 4)))
print(comb)
[[1, 2, 4, 5], [1, 2, 4, 8], [1, 2, 4, 9], [1, 2, 5, 8], [1, 2, 5, 9], [1, 2, 8, 9], [1, 4, 5, 8], [1, 4, 5, 9], [1, 4, 8, 9], [1, 5, 8, 9], [2, 4, 5, 8], [2, 4, 5, 9], [2, 4, 8, 9], [2, 5, 8, 9], [4, 5, 8, 9]]
READ ALSO
create a Dynamic mapping for parsing multiple input files to an obj in kotlin

create a Dynamic mapping for parsing multiple input files to an obj in kotlin

Let's say I have a json data that can have different Key names for the same data field

64
How can I split string by a special character and ignore everything inside parentheses?

How can I split string by a special character and ignore everything inside parentheses?

I want to split the string by "/" and ignore "/" inside the outer parentheses

81