首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >生成python中的特定排列模式

生成python中的特定排列模式
EN

Stack Overflow用户
提问于 2018-12-07 20:05:38
回答 2查看 599关注 0票数 1

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

我最初的尝试是生成这三个字符的所有可能的排列,并过滤掉任何被禁止的模式。不幸的是,对于长序列长度,排列比例很低。我解决了这个问题,方法是生成每个序列,每次一个字符,并检查我在构建序列时所设定的条件。这防止了非生产性序列的产生,并且大大减少了正在产生的排列的数量。问题是我不是一个程序员,为了达到这个目标,我不得不硬编码一堆嵌套的for-循环。下面的代码显示的字符串长度为5。

代码语言:javascript
运行
复制
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)

输出:

代码语言:javascript
运行
复制
['XYXYX', 'XYXZX', 'XZXYX', 'XZXZX', 'YXYXY', 'YXYXZ', 'YXZXY', 'YXZXZ', 'ZXYXY', 'ZXYXZ', 'ZXZXY', 'ZXZXZ']

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-07 21:47:56

对于['X','Y','Z'],有9对可以创建。但对XX, YY, ZZ, YZ, ZY是被禁止的。所以它仍然是XY,XZ,YX,ZX。将其划分为两个单元(units1units2),以避免排列中的XX。如果length是偶数,它只是使用迭代工具产品对每个单元进行置换(参见:generating permutations with repetitions in python)。它将生成可以连接到字符串的元组列表(请参阅:Why can't I join this tuple in Python?)。附上这两份名单。

对于奇数情况,单元1的组合将产生带有X前缀的任何组合,因此将'X‘附加到每个字符串的最后一个,而将Y,Z附加到begin。对于单元2组合做相反的。它不会产生唯一的列表,所以向set进行转换只是为了使其独一无二。

代码语言:javascript
运行
复制
import itertools

def combine(length):
    units1 = ['XY','XZ']
    units2 = ['YX','ZX']

    combine1 = ["".join(map(str,p)) for p in itertools.product(units1,repeat=int(length/2))]
    combine2 = ["".join(map(str,p)) for p in itertools.product(units2,repeat=int(length/2))]

    if (length%2 == 1):
        combine1_odd = [item + 'X' for item in combine1] + ['Y' + item for item in combine1] + ['Z' + item for item in combine1]
        combine2_odd = ['X' + item for item in combine2] + [item + 'Y' for item in combine2] + [item + 'Z' for item in combine2]
        return list(set(combine1_odd + combine2_odd))

    return list(set(combine1 + combine2))

print(combine(5))
票数 0
EN

Stack Overflow用户

发布于 2018-12-07 20:13:53

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

代码语言:javascript
运行
复制
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]]

输出:

代码语言:javascript
运行
复制
['XYXYX', 'XYXYZ', 'XYXZX', 'XYXZY', 'XYZXY', 'XYZXZ', 'XYZYX', 'XYZYZ', 'XZXYX', 'XZXYZ', 'XZXZX', 'XZXZY', 'XZYXY', 'XZYXZ', 'XZYZX', 'XZYZY']
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53676190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档