gpt4 book ai didi

python - 在Python中生成特定的排列模式

转载 作者:行者123 更新时间:2023-12-01 01:22:32 25 4
gpt4 key购买 nike

我正在尝试对概率系统进行建模。我正在使用的系统涉及三个元素 - 称它们为“X”、“Y”和“Z”。这些元素以特定类型的交替模式形成字符串,其中 X 必须与 Y 或 Z 交替(即禁止 XX、YY、ZZ、YZ 和 ZY 连接)。我想排列不同字符串长度的所有可能序列的列表。

我最初的尝试是生成这三个字符的所有可能的排列,并过滤掉任何被禁止的模式。不幸的是,对于长序列长度,排列的扩展性非常差。我通过生成每个序列(一次一个字符)并检查构建序列时提出的条件来解决这个问题。这可以防止很早就生成无效序列,并大大减少生成的排列数量。问题是我不太擅长编码,我必须对一堆嵌套的 for 循环进行硬编码才能实现这个目标。下面的代码显示了字符串长度为 5 的情况。

Length = 5
Units = ['X','Y','Z']
Sequences = []

#aij is the j'th character in the sequence

for i1 in range(len(Units)):
ai1 = n[i1]
for i2 in range(len(Units)):
ai2 = Units[i2]

#If the two most recent sequential units are identical OR (Y and Z) OR (Z and Y), pass

if ai2 == ai1 or ai2==Units[1] and ai1==Units[2] or ai2==Units[2] and ai1==Units[1]:
pass
else:

#repeat for the other characters in the sequence until the final character is reached

for i3 in range(len(Units)):
ai3 = Units[i3]
if ai3 == ai2 or ai3==Units[1] and ai2==Units[2] or ai3==Units[2] and ai2==Units[1]:
pass
else:
for i4 in range(len(Units)):
ai4 = Units[i4]
if ai4 == ai3 or ai4==Units[1] and ai3==Units[2] or ai4==Units[2] and ai3==Units[1]:
pass
else:
for i5 in range(len(Units)):
ai5 = Units[i5]
if ai5 == ai4 or ai5==Units[1] and ai4==Units[2] or ai5==Units[2] and ai4==Units[1]:
pass
else:

#Append the valid sequence to my list of Sequences

a = ai1 + ai2 + ai3 + ai4 + ai5
Sequences.append(a)

print(Sequences)

输出:

['XYXYX', 'XYXZX', 'XZXYX', 'XZXZX', 'YXYXY', 'YXYXZ', 'YXZXY', 'YXZXZ', 'ZXYXY', 'ZXYXZ', 'ZXZXY', 'ZXZXZ']

我的问题是,我如何将这种类型的算法推广到一个仅接受输入“长度”(即字符串中的字符数)并生成列表中的所有序列模式的函数?

最佳答案

您可以使用带有递归的生成器:

def combinations(d, _len, current = []):
if len(current) == _len:
yield current
else:
for i in d:
if not current or ('X' in current and current[-1] != i):
yield from combinations(d, _len, current+[i])


results = list(map(''.join, combinations(['X','Y','Z'], 5)))
final_results = [a for i, a in enumerate(results) if a not in results[:i]]

输出:

['XYXYX', 'XYXYZ', 'XYXZX', 'XYXZY', 'XYZXY', 'XYZXZ', 'XYZYX', 'XYZYZ', 'XZXYX', 'XZXYZ', 'XZXZX', 'XZXZY', 'XZYXY', 'XZYXZ', 'XZYZX', 'XZYZY']

关于python - 在Python中生成特定的排列模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53676190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com