def flags(d, c = []):
if len(c) == 3:
yield c
else:
for i in d:
if (c and c[-1] != i and (True if i != 'B' else len(c) == 1) and ('B' not in c or i not in c)) or (not c and i != 'B'):
yield from flags(d, c+[i])
print(list(flags(['R', 'W', 'B'])))
def blue_between(x):
if x[0]=='B':
return False
if x[-1]=='B':
return False
for i in zip(x[:-2],x[1:-1],x[2:]):
if i[1]=='B':
if not ((i[0]=='R' and i[2]=='W') or (i[0]=='W' and i[2]=='R')):
return False
return True
使用方法如下:
stripes = [s for s in stripes if blue_between(s)]
print(stripes)
from itertools import product, groupby
colors = [1, 2, 3] # 1 - red, 2 - blue, 3 - white
n = 3
output = []
for c in product(colors, repeat=n):
# do we have consecutive colors?
if max(sum(1 for _ in g) for _, g in groupby(c)) > 1:
continue
# is blue color on any end?
if c[0] == 2 or c[-1] == 2:
continue
# is blue color between same colors?
if any(c[i-1] == c[i+1] for i, v in enumerate(c) if v==2):
continue
output.append(c)
from pprint import pprint
pprint(output, width=30)
可以对生成器使用递归:
输出:
首先生成所有可能的条纹组合:
输出:
然后抛弃那些不完全符合要求的填充物,首先:没有2个颜色相同的相邻物,让功能检查一下:
然后按以下方式使用:
输出:
然后我们需要函数来检查蓝色是否总是介于白色和红色或红色和白色之间:
使用方法如下:
输出:
注意使用
zip
和索引切片来获取当前条带和下一条带或上一条带和下一条带。你知道吗使用
itertools.product
获取所有可能的组合,使用itertools.groupby
检查彼此之间是否没有任何相同颜色的条纹:印刷品:
相关问题 更多 >
编程相关推荐