我在尝试建立一个概率系统的模型。我正在使用的系统包含三个元素—称它们为“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']
我的问题是,如何将这类算法推广到一个函数,该函数只接受输入的“长度”(即字符串中的字符数)并在一个列表中生成我的所有序列模式?
可以使用带递归的生成器:
输出:
对于
['X','Y','Z']
,可以创建9对。但是对XX, YY, ZZ, YZ, ZY
是禁止的。所以它仍然是XY,XZ,YX,ZX
。把它分成两个单位(units1
和units2
),以避免XX
的排列。如果length
是偶数,它只需使用itertools乘积对每个单元进行排列(请参见:generating permutations with repetitions in python)。它将生成可以连接到字符串的元组列表(请参见:Why can't I join this tuple in Python?)。把那两张单子加在后面。你知道吗对于奇数情况,单元1的组合将产生任何带有
X
前缀的组合,因此在每个字符串的最后一个字符串后面加上“X”,在开始处加上Y,Z
。对于单位2的组合做相反的。它不会产生唯一的列表,所以转换到set
只是为了使它唯一相关问题 更多 >
编程相关推荐