-2

I want to get all possible combinations of 1 and 2 that 2s are not besides together. for example, if n=3, then I want a list like this:

    111
    121
    211
    112
    212
    ...

Thank you for any help that you can provide.

Zahra Hosseini
  • 478
  • 2
  • 4
  • 14
  • Simple approach: `list(filter(lambda p: "22" not in p, map("".join, itertools.product("12", repeat=n))))` – Samwise Aug 29 '21 at 14:46

2 Answers2

0

Use itertools.product, then filter out the 22:

from itertools import product

values, n = "12", 3
result = [r for x in product(values, repeat=n)
          if "22" not in (r := "".join(x))]
print(result)  # ['111', '112', '121', '211', '212']
azro
  • 53,056
  • 7
  • 34
  • 70
0
from itertools import product 
    
N = 6
n_prod = list(product(['1','2'],repeat=N))
[x for x in list(map(lambda x: ''.join(x), n_prod)) if '22' not in x]

But maybe it's too overweight... Maybe better use

from random import choice
choice([1,2])
ooolllooo
  • 353
  • 1
  • 3
  • 11