首页 > 解决方案 > 如何使用python限制相同字母的最长序列

问题描述

如何使用python确定同一字母的最长序列?

例如,我使用以下代码打印具有 3 个条件 A、B 和 C 的混洗列表

from random import shuffle
condition = ["A"]*20
condition_B = ["B"]*20
condition_C = ["C"]*20

condition.extend(condition_B)
condition.extend(condition_C)
shuffle(condition)
print(condition)

现在我想确保相同的情况不会连续发生超过 3 次。

例如,允许:[A,B,C,A,B,B,C,C,C,A,B……] 不允许:[A,A,B,B,B,B,C,A,B ...](因为连续四个 B)

我怎么解决这个问题?先感谢您。

标签: pythonpython-3.6

解决方案


也许您应该按顺序构建列表,而不是改组:

result = []
for i in range(60):     # for each item in original list
  start = true          # we haven't found a suitable one yet
  if start or i>2:      # don't do checking unless 3 items in list
    while start or (
           c==shuf[-1] and     # is the chosen value
           c==shuf[-2] and     # the same as any of
           c==shuf[-3] ):      # the last 3 items?
      idx = random.randint(0,len(condition))  # chose a new one
      c = condition[idx]
      start = false            
  result.append(c)      # add to result
  del condition[i]      # remove from list

警告!未经测试 - 只是概念...


推荐阅读