如何仅使用' O'来打印给定长度的所有序列?或者' Z'在python?

时间:2018-06-09 11:07:37

标签: python python-3.x

如何在Python中仅使用'O''Z'打印给定长度的所有序列?

例如,如果我提供length = 3

输出将是:

'OOO'
'OOZ'
'OZO'
'OZZ'
'ZOO'
'ZZO'
'ZOZ'
'ZZZ'

1 个答案:

答案 0 :(得分:1)

您可以使用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']