L'algorithme par geocar échoue lorsque:
s=[tp(0,1),tp(0,3)]
Je ne suis pas très sûr, mais je pense que cela est la bonne façon:
class tp():
def __repr__(self):
return '(%.2f,%.2f)' % (self.start, self.end)
def __init__(self,start,end):
self.start=start
self.end=end
s=[tp(0,1),tp(0,3),tp(4,5)]
s.sort(key=lambda self: self.start)
print s
y=[ s[0] ]
for x in s[1:]:
if y[-1].end < x.start:
y.append(x)
elif y[-1].end == x.start:
y[-1].end = x.end
if x.end > y[-1].end:
y[-1].end = x.end
print y
Je l'ai également mis en œuvre pour la soustraction:
#subtraction
z=tp(1.5,5) #interval to be subtracted
s=[tp(0,1),tp(0,3), tp(3,4),tp(4,6)]
s.sort(key=lambda self: self.start)
print s
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
print s
Je pense que la dernière déclaration 'elif' devrait être à la recherche de chevauchement, pas nécessairement un strict égal; et ensuite l'assignation finale doit prendre la plus grande de 'y [-1] .end' ou' x.end'. Par exemple, voir ce qui suit: 's = [tp (1,4), tp (6,8), tp (7,10)]' – Noah