1

How can I print all sequences of a given length using only 'O' or 'Z' in Python?

For example, if I give length = 3

the output would be:

'OOO'
'OOZ'
'OZO'
'OZZ'
'ZOO'
'ZZO'
'ZOZ'
'ZZZ'
Ivan
  • 24,563
  • 6
  • 44
  • 76
Madfish
  • 85
  • 6
  • 4
    http://idownvotedbecau.se/noattempt/ - SO is about fixing _your_ Code - not implementing your ideas. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [minimal verifyable complete example](https://stackoverflow.com/help/mcve). – Patrick Artner Jun 09 '18 at 11:18

1 Answers1

1

You can achieve this by generating the cartesian product of the elements using itertools:

import itertools

letters = ["O", "Z"]
length = 3

vals = [''.join(comb) for comb in itertools.product(letters, repeat=length)]

print(vals)
>>>['OOO', 'OOZ', 'OZO', 'OZZ', 'ZOO', 'ZOZ', 'ZZO', 'ZZZ']
Olivier Melançon
  • 20,340
  • 3
  • 37
  • 69
iacob
  • 14,010
  • 5
  • 54
  • 92