我正在尝试编写一些代码来计算两组区间 A - B 的差,区间端点为整数,但我很难想出有效的解决方案,如有任何建议,将不胜感激。
示例:[(1, 4), (7, 9)] - [(3,5)] = [(1, 3), (7, 9)]
示例:[(1, 4), (7, 9)] - [(3,5)] = [(1, 3), (7, 9)]
这是迄今为止我所尝试的最佳方法(两个列表已经排序)
class tp():
def __repr__(self):
return '(%.2f,%.2f)' % (self.start, self.end)
def __init__(self,start,end):
self.start=start
self.end=end
z=[tp(3,5)] #intervals to be subtracted
s=[tp(1, 4)),tp(7, 9), tp(3,4),tp(4,6)]
for x in s[:]:
if z.end < x.start:
break
elif z.start < x.start and z.end > x.start and z.end < x.end:
x.start=z.end
elif z.start < x.start and z.end > x.end:
s.remove(x)
elif z.start > x.start and z.end < x.end:
s.append(tp(x.start,z.start))
s.append(tp(z.end,x.end))
s.remove(x)
elif z.start > x.start and z.start < x.end and z.end > x.end:
x.end=z.start
elif z.start > x.end:
continue
s=[tp(1, 4)),tp(7, 9), tp(3,4),tp(4,6)]
并没有按照任何明显的排序方式进行排序。此外,你的代码似乎假设z
是一个单独的tp
,但是你的例子显示它是一个列表。能否请你澄清一下你的期望? - rici