0

Hello I have tried using this tool:

list(combinations('01', 3))

but I get this result:

[]

I would like to have these results:

000
001
011
111
101
100
010

Separately, I would also like to have different cases.

for instance, given 111 I expect these results:

111
12
21
3

Is it possible to do these two things using itertools?

pylang
  • 40,867
  • 14
  • 129
  • 121

2 Answers2

0

Here's a solution which is partially using the solution in this answer.

  • The partition function from alexis' answer (see link) returns the list partitioned into groups (i.e. [[[1,1,1]],[[1,1],[1]],[[1],[1,1]],[[1],[1],[1]]]
  • To get the numbers in your question, I added a part that stores only the sum of each inner list
  • list(dict.fromkeys(...)) is used to remove duplicates

Code

def partition(collection):
    if len(collection) == 1:
        yield [ collection ]
        return

    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[ first ] + subset]  + smaller[n+1:]
        # put `first` in its own subset 
        yield [ [ first ] ] + smaller


elements = list([1,1,1])

lst = list(dict.fromkeys([ tuple([sum(p[1][i]) for i in range(len(p[1]))]) for p in enumerate(partition(elements), 1) ]))

print(sorted(lst))

Output:

[(1, 1, 1), (1, 2), (2, 1), (3,)]
DenverCoder1
  • 2,253
  • 1
  • 10
  • 23
  • If you want it to print as `111 12 21 3`, you can do `print(' '.join([''.join([str(i) for i in j]) for j in lst]))` – DenverCoder1 Oct 07 '19 at 18:20
0

You seem to be asking two separate questions. Based on your results:

  1. 000 001 011 111 101 100 010

Use a permutations_with_replacement combinatoric via itertools.product.

  1. 111 12 21 3

Use a partitions algorithm via more_itertools.partitions.

Given

import itertools as it

import more_itertools as mit

Code

# 1 - Permutation w Replacement
>>> list(it.product("01", repeat=3))
[('0', '0', '0'),
 ('0', '0', '1'),
 ('0', '1', '0'),
 ('0', '1', '1'),
 ('1', '0', '0'),
 ('1', '0', '1'),
 ('1', '1', '0'),
 ('1', '1', '1')]

# 2 - Partitions
>>> list(mit.partitions("111"))
[[['1', '1', '1']],
 [['1'], ['1', '1']],
 [['1', '1'], ['1']],
 [['1'], ['1'], ['1']]]

Details

To achieve your specific results, use list comprehensions:

# 1
>>> ["".join(x) for x in it.product("01", repeat=3)]

['000', '001', '010', '011', '100', '101', '110', '111']

# 2
>>> [[sum(map(int, x)) for x in sub] for sub in mit.partitions("111")]

[[3], [1, 2], [2, 1], [1, 1, 1]]

more_itertools is a third-party package. Install with > pip install more-itertools.

pylang
  • 40,867
  • 14
  • 129
  • 121