【发布时间】: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