【问题标题】:Create a Sequence With Two of Each Element Satisfying Certain Distance Criteria创建一个序列,其中每个元素中的两个满足特定距离标准
【发布时间】:2019-10-29 11:59:37
【问题描述】:

给定一系列不同的项目 Sa,我们希望创建一个序列 Sb(由 Sa 中的相同项目组成,但顺序不同),使得序列 S = Sa + Sb(序列 Sb 紧跟在序列 Sa 之后) 满足以下性质:

  • 对于所有项目 I,项目 I 在 S 中的两次出现之间的距离(位置数)至少是某个数字 T。
  • 如果项目 I 和 J 在 Sa 的 N 个位置内,则 I 和 J 不在 Sb 的 N 个位置内。

我已经能够相当简单地用 Python 编写第一个规定。然而,第二个是我挣扎的地方。本质上,我只想要这两件事:

  • 我希望第二个序列的项目与其在第一个序列中的出现“足够远”。
  • 我不希望第一个序列的邻居也成为第二个序列中的邻居(N 指的是项目被视为邻居的距离)。

这是我目前所拥有的:

import random

clips = list(range(10)) # arbitrary items
choice_pool = clips[:]
Sa = clips[:]
random.shuffle(Sa)
Sb = []
count = len(Sa)

threshold = 0.5*len(clips) # the minimum distance the item has to be away from itself in the concatenated sequence
while len(Sb) != len(Sa):
    jj = random.randint(0, len(choice_pool) - 1)
    # we want clip a1 to be at least threshold away from clip b1
    if count - Sa.index(choice_pool[jj]) >= threshold:
        Sb.append(choice_pool[jj])
        del choice_pool[jj]
        count += 1

print("Sa:", Sa)
print("Sb:", Sb)
print("S :", Sa + Sb)

您对如何同时实现第二条规定有任何建议,同时始终保证存在这样的序列(不会以无限循环结束)?谢谢。

【问题讨论】:

  • any Sb 会去吗,或者您需要一种随机选择 all 此类安排之一的方法?
  • @user58697,我需要一种随机选择所有此类安排的方法。

标签: python algorithm list sequence permutation


【解决方案1】:

我会从等式中排除随机性的机会。随机性永远无法保证您不会陷入无限循环。此算法有更好的改进,但这是基础。

import itertools as it

def filter_criteria(sequence):
    #put your filters here return True if you find a sequence that works
    pass 

for sb_try in it.permutations(sa, len(sa)):
   if filter_criteria(sa+sb_try):
       return sb_try

return "no permutation matches"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2016-09-13
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多