【问题标题】:Find all possible combinations that overlap by end and start找出所有可能在结束和开始之前重叠的组合
【发布时间】:2020-05-10 06:15:26
【问题描述】:

在帖子find all combinations with non-overlapped regions(粘贴在下面的代码)中,该函数被赋予了一组元组,它递归地查找具有非重叠值的每个可能的元组集合。例如,在元组列表T = [(0.0, 2.0), (0.0, 4.0), (2.5, 4.5), (2.0, 5.75), (2.0, 4.0), (6.0, 7.25)] 上,我们得到

def nonovl(l, idx, right, ll):
    if idx == len(l):
        if ll:
            print(ll)
        return

    next = idx + 1  
    while next < len(l) and right >= l[next][0]:
        next += 1
    nonovl(l, next, right, ll)

    next = idx + 1
    right = l[idx][1]
    while next < len(l) and right >= l[next][0]:
        next += 1
    nonovl(l, next, right, ll + str(l[idx]))

>>> T = [(0.0, 2.0), (0.0, 4.0), (2.5, 4.5), (2.0, 5.75), (2.0, 4.0), (6.0, 7.25)]
>>> l.sort()
>>> nonovl(l, 0, -1, "")
(6.0, 7.25)
(2.5, 4.5)
(2.5, 4.5)(6.0, 7.25)
(2.0, 5.75)
(2.0, 5.75)(6.0, 7.25)
(2.0, 4.0)
(2.0, 4.0)(6.0, 7.25)
(0.0, 4.0)
(0.0, 4.0)(6.0, 7.25)
(0.0, 2.0)
(0.0, 2.0)(6.0, 7.25)
(0.0, 2.0)(2.5, 4.5)
(0.0, 2.0)(2.5, 4.5)(6.0, 7.25)

我们如何修改nonovl() 函数,使其允许两个元组的开始和结束值重叠的组合?例如,在同一个列表上运行它,我们会得到:

(0.0, 2.0)(2.0, 4.0)(6.0, 7.25)

【问题讨论】:

    标签: python list sorting recursion dynamic-programming


    【解决方案1】:

    &gt;= 更改为&gt;。现在,如果“下一个”元组的左索引值小于或等于“下一个”元组的右索引值,代码将跳过“下一个”元组当前”元组。它找到第一个左索引值严格大于当前元组右索引值的元组。

    def nonovl(l, idx, right, ll):
        if idx == len(l):
            if ll:
                print(ll)
            return
    
        next = idx + 1  
        while next < len(l) and right > l[next][0]:
            next += 1
        nonovl(l, next, right, ll)
    
        next = idx + 1
        right = l[idx][1]
        while next < len(l) and right > l[next][0]:
            next += 1
        nonovl(l, next, right, ll + str(l[idx]))
    

    输出:

    (6.0, 7.25)
    (2.5, 4.5)
    (2.5, 4.5)(6.0, 7.25)
    (2.0, 5.75)
    (2.0, 5.75)(6.0, 7.25)
    (2.0, 4.0)
    (2.0, 4.0)(6.0, 7.25)
    (0.0, 4.0)
    (0.0, 4.0)(6.0, 7.25)
    (0.0, 2.0)
    (0.0, 2.0)(6.0, 7.25)
    (0.0, 2.0)(2.5, 4.5)
    (0.0, 2.0)(2.5, 4.5)(6.0, 7.25)
    (0.0, 2.0)(2.0, 5.75)
    (0.0, 2.0)(2.0, 5.75)(6.0, 7.25)
    (0.0, 2.0)(2.0, 4.0)
    (0.0, 2.0)(2.0, 4.0)(6.0, 7.25)
    

    【讨论】:

    • 谢谢!有没有办法进一步改变它,以便这些输出可以成为一个或多个元组的列表,而不是以字符串格式打印?使用上述数据,结果将是[[(6.0, 7.25)], [(2.5, 4.5)], [(2.5, 4.5), (6.0, 7.25)], ..., [(0.0, 2.0), (2.0, 4.0), (6.0, 7.25)]]。我对递归没有太多经验,在尝试将每个步骤附加到列表时遇到各种错误。
    • 我在上面评论中的问题似乎有点复杂,所以我在这里单独提出一个问题:stackoverflow.com/questions/59901396/…
    • 变化不大。您可以做的是在外面创建一个空列表并填写它而不是打印。我将在您的其他页面中详细说明作为答案。
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2017-03-31
    • 2014-08-20
    相关资源
    最近更新 更多