Python graph traversal and use of weak references

Source: Internet
Author: User
A piece of code seen in the [python standard library] is very helpful:

def all_nodes(self):        yield self        n = self.other        while n and n.name != self.name:            yield n            n = n.other        if n is self:            yield n        return


Yield at the beginning and end of the cycle graph is returned only once, as the starting point and ending point of the cycle graph, and n as the potential node of the graph. the next node is returned in each next call.

With this iterator, you can easily print the structure of the plot:

Def _ str _ (self ):

Return '->'. join (n. name for n in self. all_nodes ()))


Graph:

One-> two-> three-> one


To implement a graph structure, you must use the weak references in python,

Let's take a look at the code of adding the next node to the standard graph structure:

Def set_next (self, other ):

Print '% s. next % R' % (self. name, other)

Self. other = other


After binding, add a reference to the next node in the attribute field.

C. _ dict __

{'Other ': , 'Name': '1 '}


Therefore, even if you manually call a = None, B = None, c = None, the object will not be deleted.

Garbage :[ ,

,

,

{'Name': 'one', 'other ': },

{'Name': 'two', 'other ': },

{'Name': 'Three ', 'other ': }]

Weak references refer to "referencing an object without increasing the pointer count of the referenced object"

You can use c = weekref. ref (k, func)

To specify the referenced object and the action func after the object is deleted.

When calling, use c () to reference k

However, in the previous example, we need a "proxy object" to proxy the referenced object, so that the set_next function can be used as the variable other with the normal variable.

def set_next(self, other):        if other is not None:            if self in other.all_nodes():                other = weakref.proxy(other)        super(WeakGraph, self).set_next(other)        return


This avoids the use of other () to reference an other object ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.