MCPcopy Create free account
hub / github.com/ActiveState/code / discard

Method discard

recipes/Python/578615_graph/recipe-578615.py:440–478  ·  view source on GitHub ↗

Remove vertices and/or edges. Parameters can be single vertex or list of vertices. If tail is empty, then vertex deletions are made and any connected edges. >>> g = Graph() >>> g.add(range(3), range(4)) >>> g.discard(1) #remove vertex 1 >>> g.

(self, head, tail=[])

Source from the content-addressed store, hash-verified

438 self[h].add(tail, edge_value)
439
440 def discard(self, head, tail=[]):
441 """Remove vertices and/or edges. Parameters can be single vertex or list of vertices.
442 If tail is empty, then vertex deletions are made and any connected edges.
443
444 >>> g = Graph()
445 >>> g.add(range(3), range(4))
446 >>> g.discard(1) #remove vertex 1
447 >>> g.discard(10) #discard of non-existent vertex ignored
448 >>> g.discard([1]) #list with single vertex is fine
449 >>> g.discard([1, 3]) #discards vertices in list
450 >>> print g
451 {0: {0, 2}, 2: {0, 2}}
452
453 If tail is non-empty, then only edge deletions are made.
454 >>> g.discard(0, 2) #discard edge
455 >>> g.discard(5, 0) #non-existent edge ignored
456 >>> g.discard(2, [1, 0, 2, 2]) #will discard two actual edges
457 >>> print g
458 {0: {0}, 2: {}}
459 """
460 if tail==[]: #vertex deletions
461 try:
462 del self[head]
463 except LookupError: pass #do nothing if given non-existent vertex
464 except TypeError, error: #given head list
465 if not isinstance(head, list): raise TypeError(error)
466 for h in head[:]: #must use copy since removing below
467 if h in self:
468 self[h].clear()
469 super(Graph, self).__delitem__(h) #don't duplicate effort (will discard in_vertices below)
470 else: head.remove(h) #for faster tail removal in next loop
471 for h in self.itervalues(): #visit remaining vertices and remove occurances of head items in edge lists
472 h.discard(head)
473 else: #edge deletions only
474 if not isinstance(head, list): head = [head] #quick and dirty to avoid extra code
475 for h in head:
476 if h in self:
477 self[h].discard(tail)
478 if _DEBUG: self._validate()
479
480 def __contains__(self, vid): #XXX probably slows things down for little value?
481 """Returns non-zero if v in self. If a list is given, all

Callers 10

toposort2Function · 0.45
friendsFunction · 0.45
recipe-578447.pyFile · 0.45
try_maskingFunction · 0.45
gprofileFunction · 0.45
fix_paneMethod · 0.45
__delitem__Method · 0.45
fix_paneMethod · 0.45
__delitem__Method · 0.45

Calls 5

_validateMethod · 0.95
clearMethod · 0.45
__delitem__Method · 0.45
removeMethod · 0.45
itervaluesMethod · 0.45

Tested by

no test coverage detected