Advanced data structure in Python detailed _python

Source: Internet
Author: User
Tags assert class manager mixed shallow copy pprint in python

Data

The concept of data structures is well understood, which is the structure used to organize data together. In other words, the data structure is what is used to store a series of associated data. There are four types of built-in data structures in Python, list, Tuple, dictionary, and set. Most applications do not require other types of data structures, but there are a number of advanced data structures to choose from, such as collection, Array, HEAPQ, bisect, Weakref, copy, and Pprint. This article describes the use of these data structures to see how they help our applications.

The use of four built-in data structures is simple and there are many references on the web, so this article will not discuss them.

1. Collections

The collections module contains useful tools beyond the built-in types, such as counter, Defaultdict, Ordereddict, deque, and Nametuple. where counter, deque, and defaultdict are the most commonly used classes.

1.1 Counter ()

If you want to count the number of occurrences of a word in a given sequence, such operations can be used for counter. To see how to count the number of item occurrences in a list:

Copy Code code as follows:

From collections Import Counter

Li = ["Dog", "Cat", "Mouse", "Dog", "" "," Cat "," Dog "]
A = Counter (LI)
Print a # Counter ({' Dog ': 3, 42:2, ' Cat ': 2, ' Mouse ': 1})

To count the number of different words in a list, you can do so by:

Copy Code code as follows:

From collections Import Counter

Li = ["Dog", "Cat", "Mouse", "Dog", "" "," Cat "," Dog "]
A = Counter (LI)
Print a # Counter ({' Dog ': 3, 42:2, ' Cat ': 2, ' Mouse ': 1})

Print Len (set (LI)) # 4

If you need to group the results, you can do this:

Copy Code code as follows:

From collections Import Counter

Li = ["Dog", "Cat", "Mouse", "Dog", "Cat", "Dog"]
A = Counter (LI)

Print a # Counter ({' Dog ': 3, ' Cat ': 2, ' Mouse ': 1})

print ' {0}: {1} '. Format (A.values (), A.keys ()) # [1, 3, 2]: [' Mouse ', ' Dog ', ' Cat ']

Print (A.most_common (3)) # [(' Dog ', 3), (' Cat ', 2), (' Mouse ', 1)]

The following code fragment finds the most frequently occurring word in a string and prints the number of occurrences.

Copy Code code as follows:



Import re


From collections Import Counter





String = "" "Lorem ipsum dolor sit amet, consectetur


Adipiscing elit. Nunc ut elit id mi ultricies


Adipiscing. Nulla Facilisi. Praesent Pulvinar,


Sapien vel feugiat vestibulum, nulla dui pretium,


Non ultricies elit lacus quis ante. Lorem ipsum dolor


Sit amet, consectetur adipiscing elit. Aliquam


Pretium ullamcorper Urna quis iaculis. Etiam ac Massa


Sed turpis tempor luctus. Curabitur sed nibh eu elit


Mollis Congue. Praesent ipsum diam, Consectetur vitae


Ornare A, aliquam a nunc. In ID magna pellentesque


Tellus posuere adipiscing. Sed non mi metus, at Lacinia


Augue. Sed magna Nisi, ornare in mollis, mollis


Sed nunc. Etiam at Justo in Leo Congue mollis.


Nullam in Neque eget metus hendrerit scelerisque


EU non enim. Ut malesuada lacus eu nulla bibendum


ID euismod urna sodales. """





Words = Re.findall (R ' \w+ ', string) #This finds words in the document





Lower_words = [Word.lower () for word in words] #lower all the words





word_counts = Counter (lower_words) #counts the number each time a word appears


Print Word_counts





# Counter ({' Elit ': 5, ' sed ': 5, ' in ': 5, ' adipiscing ': 4, ' mollis ': 4, ' EU ': 3,


# ' ID ': 3, ' Nunc ': 3, ' Consectetur ': 3, ' non ': 3, ' ipsum ': 3, ' nulla ': 3, ' pretium ':


# 2, ' Lacus ': 2, ' Ornare ': 2, ' at ': 2, ' praesent ': 2, ' Quis ': 2, ' sit ': 2, ' Congue ': 2, ' Amet ': 2


# ' Etiam ': 2, ' Urna ': 2, ' a ': 2, ' Magna ': 2, ' Lorem ': 2, ' Aliquam ': 2, ' UT ': 2, ' ultricies ': 2, ' mi ': 2,


# ' dolor ': 2, ' metus ': 2, ' AC ': 1, ' Bibendum ': 1, ' posuere ': 1, ' enim ': 1, ' ante ': 1, ' sodales ': 1, ' Tellus ': 1,


# ' vitae ': 1, ' DUI ': 1, ' diam ': 1, ' pellentesque ': 1, ' Massa ': 1, ' vel ': 1, ' Nullam ': 1, ' feugiat ': 1, ' luctus ': 1,


# ' Pulvinar ': 1, ' Iaculis ': 1, ' hendrerit ': 1, ' Orci ': 1, ' Turpis ': 1, ' nibh ': 1, ' scelerisque ': 1, ' ullamcorper ': 1,


# ' eget ': 1, ' neque ': 1, ' euismod ': 1, ' Curabitur ': 1, ' Leo ': 1, ' sapien ': 1, ' Facilisi ': 1, ' vestibulum ': 1, ' nisi ': 1,


# ' Justo ': 1, ' augue ': 1, ' Tempor ': 1, ' Lacinia ': 1, ' Malesuada ': 1}


1.2 Deque

Deque is a two-terminal queue (double-ended queue) that is extended by the queue structure, which can be added or deleted at both ends of the queue. So it is also called the head-tail linked list, although there is another special data structure implementation called the name.

Deque supports thread-safe, optimized append and pop operations, and the associated operations at both ends of the queue can be nearly O (1) time complexity. Although the list also supports similar operations, however, it is very good for a fixed-length list, and when you encounter a pop (0) and insert (0, V) that change the length of the list and change its element position, the complexity becomes O (n).

Take a look at the relevant comparison results:

Copy Code code as follows:



Import time


From collections Import Deque





num = 100000





def append (c):


For I in range (num):


C.append (i)





def appendleft (c):


If Isinstance (c, deque):


For I in range (num):


C.appendleft (i)


Else


For I in range (num):


C.insert (0, I)


def pop (c):


For I in range (num):


C.pop ()





def popleft (c):


If Isinstance (c, deque):


For I in range (num):


C.popleft ()


Else


For I in range (num):


C.pop (0)





For container in [Deque, List]:


For operation in [Append, Appendleft, Pop, Popleft]:


c = container (range (num))


Start = Time.time ()


Operation (c)


elapsed = Time.time ()-Start


print ' Completed {0}/{1} in {2} seconds: {3} ops/sec '. Format (


container.__name__, operation.__name__, elapsed, num/elapsed)





# Completed Deque/append in 0.0250000953674 seconds:3999984.74127 ops/sec


# Completed Deque/appendleft in 0.0199999809265 seconds:5000004.76838 ops/sec


# Completed Deque/pop in 0.0209999084473 seconds:4761925.52225 ops/sec


# Completed Deque/popleft in 0.0199999809265 seconds:5000004.76838 ops/sec


# Completed List/append in 0.0220000743866 seconds:4545439.17637 ops/sec


# Completed List/appendleft in 21.3209998608 seconds:4690.21155917 ops/sec


# Completed List/pop in 0.0240001678467 seconds:4166637.52682 ops/sec


# Completed List/popleft in 4.01799988747 seconds:24888.0046791 ops/sec


Another example is to perform basic queue operations:

Copy Code code as follows:

From collections Import Deque
Q = deque (range (5))
Q.append (5)
Q.appendleft (6)
Print Q
Print Q.pop ()
Print Q.popleft ()
Print Q.rotate (3)
Print Q
Print Q.rotate (-1)
Print Q

# deque ([6, 0, 1, 2, 3, 4, 5])
# 5
# 6
# None
# deque ([2, 3, 4, 0, 1])
# None
# deque ([3, 4, 0, 1, 2])


Translator Note: Rotate is the rotation operation of the queue, right rotate (positive argument) is to move the elements on the right-hand side to the left, while the left-hand rotate (negative) is the opposite.

1.3 defaultdict

This type is identical to the normal dictionary except for the operation of a nonexistent key. When a nonexistent key operation is found, its default_factory is invoked, provides a default value, and stores the key value. Other parameters are consistent with the normal Dictionary method Dict (), and a defaultdict instance has the same operation as the built-in Dict.

The Defaultdict object is useful when you want to use it to store trace data. For example, suppose you want to track the position of a word in a string, so you can do this:

Copy Code code as follows:

From collections Import Defaultdict

s = "The quick brown fox jumps over the lazy dog"

Words = S.split ()
Location = defaultdict (list)
For M, N in Enumerate (words):
Location[n].append (M)

Print location

# defaultdict (<type ' list ', {' Brown ': [2], ' lazy ': [7], ' over ': [5], ' Fox ': [3],
# ' dog ': [8], ' Quick ': [1], ' the ': [0, 6], ' Jumps ': [4]}]

Choosing lists or sets with defaultdict depends on your purpose, using list to save the order in which you insert elements, and using set does not care about the insertion order of elements, it helps eliminate duplicate elements.

Copy Code code as follows:

From collections Import Defaultdict

s = "The quick brown fox jumps over the lazy dog"

Words = S.split ()
Location = Defaultdict (set)
For M, N in Enumerate (words):
Location[n].add (M)

Print location

# defaultdict (<type ' set ', {' Brown ': Set ([2]), ' lazy ': Set ([7]),
# ' over ': Set ([5]), ' Fox ': Set ([3]), ' Dog ': Set ([8]), ' Quick ': Set ([1]),
# ' the ': set ([0, 6]), ' jumps ': Set ([4])})

Another way to create a multidict:

Copy Code code as follows:

s = "The quick brown fox jumps over the lazy dog"
D = {}
Words = S.split ()

For key, value in enumerate (words):
D.setdefault (key, []). Append (value)
Print D

# {0: [' the '], 1: [' Quick '], 2: [' Brown '], 3: [' Fox '], 4: [' Jumps '], 5: [' over '], 6: [' The '], 7: [' lazy '], 8: [' Dog ']}

A more complex example:

Copy Code code as follows:

Class Example (Dict):
def __getitem__ (self, item):
Try
Return dict.__getitem__ (self, item)
Except Keyerror:
Value = Self[item] = Type (self) ()
return value

A = Example ()

A[1][2][3] = 4
A[1][3][3] = 5
a[1][2][' Test ' = 6

Print a # {1: {2: {' Test ': 6, 3:4}, 3: {3:5}}}

2. Array
the array module defines a new object type that is much like a list, except that it qualifies the type to fit only one type of element. The type of the array element is determined when it is created and used.

If your program needs to optimize the use of memory, and you are sure that you want the data stored in the list to be the same type, it is appropriate to use the array module. For example, if you need to store 10 million integers, if you use a list, you need at least 160MB of storage space, but if you use array, you only need 40MB. But while it's possible to save space, there's little basic operation on the array that can be faster than the list.

When you use array for calculations, you need to pay special attention to the actions that create the list. For example, when using a list comprehension, the entire array is converted to list, which expands the storage space. A viable alternative is to use a builder expression to create a new array. Look at the code:


Copy Code code as follows:

Import Array

A = Array.array ("i", [1,2,3,4,5])
b = Array.array (A.typecode, (2*x for x in a))

Because array is used to conserve space, it is more likely to use in-place operations. A more efficient approach is to use enumerate:

Copy Code code as follows:

Import Array

A = Array.array ("i", [1,2,3,4,5])
For I, X in Enumerate (a):
A[i] = 2*x

For a larger array, this in-place modification can increase the speed of at least 15% faster than creating a new array with the generator.

So when do you use array? is when you are considering the factors of calculation, you need to get an array of the same type of elements as the C language.

Copy Code code as follows:

Import Array
From Timeit import Timer

Def arraytest ():
A = Array.array ("i", [1, 2, 3, 4, 5])
b = Array.array (A.typecode, (2 * x for x in a))

Def enumeratetest ():
A = Array.array ("i", [1, 2, 3, 4, 5])
For I, X in Enumerate (a):
A[i] = 2 * x

If __name__== ' __main__ ':
m = Timer ("Arraytest ()", "from __main__ import Arraytest")
n = Timer ("Enumeratetest ()", "from __main__ import Enumeratetest")

Print M.timeit () # 5.22479210582
Print N.timeit () # 4.34367196717

3.Heapq

The HEAPQ module uses a heap-implemented priority queue. A heap is a simple ordered list, and it is placed in the relevant rules of the heap.

A heap is a tree-shaped data structure in which there is a sequential relationship between the child nodes on the tree and the parent node. A binary heap (binary heap) can be identified by an organized list or array structure in which the number of child nodes of element N is 2*n+1 and 2*n+2 (subscript starting at 0). In short, all functions in this module assume that the sequence is ordered, so the first element in the sequence (Seq[0]) is the smallest, and the other parts of the sequence form a binary tree, and the Seq[i node's subnodes are seq[2*i+1] and seq[2*i+2]. When you modify a sequence, the correlation function always ensures that the child node is greater than or equal to the parent node.

Copy Code code as follows:

Import HEAPQ

heap = []

For value in [20, 10, 30, 50, 40]:
Heapq.heappush (heap, value)

While Heap:
Print Heapq.heappop (heap)

The HEAPQ module has two functions nlargest () and Nsmallest (), as the name suggests, let's look at their usage.

Copy Code code as follows:

Import HEAPQ

Nums = [1, 8, 2, 23, 7,-4, 18, 23, 42, 37, 2]
Print (Heapq.nlargest (3, Nums)) # prints [42, 37, 23]
Print (Heapq.nsmallest (3, Nums)) # prints [-4, 1, 2]

Two functions can also use a more complex data structure through a key parameter, such as:

Copy Code code as follows:

Import HEAPQ
 
Portfolio = [
{' name ': ' IBM ', ' shares ': MB, ' Price ': 91.1},
{' name ': ' AAPL ', ' shares ': ' $ ', ' price ': 543.22},
{' name ': ' FB ', ' shares ': ' "Price ': 2 1.09},
{' name ': ' HPQ ', ' shares ': $, ' Price ': 31.75},
{' name ': ' YHOO ', ' shares ': ', ' Price ': 16.35},
{' Name ': ' ACME ', ' shares ': 115.65}
]
cheap = heapq.nsmallest (3, Portfolio, Key=lambda s:s[' price ')
expensive = Heapq.nlargest (3, Portfolio, Key=lambda s:s[' price '])
 
Print cheap
  # [{' Price ': 16.35, ' name ': ' YHOO ', ' shares ':],
# {' Price ': 21.09, ' name ': ' FB ', ' shares ': +}, {' Price ': 31. , ' name ': ' HPQ ', ' shares ': '
 
Print expensive
 
# [{' Price ': 543.22, ' name ': ' AAPL ', ' shares ': {' price ': 115.65, ' name ': ' ACME ',
# ' shares ': $}, {' Price ': 91.1, ' name ': ' IBM ', ' shares ': 100}]

Take a look at how to implement a queue example that sorts according to a given priority, and each pop operation returns the highest priority element.

Copy Code code as follows:



Import HEAPQ





Class Item:


def __init__ (self, name):


Self.name = Name





def __repr__ (self):


Return ' Item ({!r}) '. Format (self.name)





Class Priorityqueue:


def __init__ (self):


Self._queue = []


Self._index = 0





def push (self, item, priority):


Heapq.heappush (Self._queue, (-priority, Self._index, item))


Self._index + 1





def pop (self):


Return Heapq.heappop (Self._queue) [-1]





Q = Priorityqueue ()


Q.push (Item (' foo '), 1)


Q.push (Item (' Bar '), 5)


Q.push (Item (' spam '), 4)


Q.push (Item (' Grok '), 1)





Print Q.pop () # Item (' bar ')


Print Q.pop () # Item (' spam ')


Print Q.pop () # Item (' foo ')


Print Q.pop () # Item (' Grok ')


4. bisect

The Bisect module can provide support for keeping list element sequences. It uses a two-point method to do most of the work. It keeps the list in order while inserting elements into a list. In some cases, this is more efficient than repeating a list, and for a larger list it is more efficient to maintain order for each step of the operation than to sort it.

Let's say you have a range collection:

Copy Code code as follows:

A = [(0, 100), (150, 220), (500, 1000)]

If I want to add a range (250, 400), I might do this:

Copy Code code as follows:

Import bisect

A = [(0, 100), (150, 220), (500, 1000)]

Bisect.insort_right (A, (250,400))

Print a # [(0, 100), (150, 220), (250, 400), (500, 1000)]

We can use the bisect () function to find the insertion point:

Copy Code code as follows:

Import bisect

A = [(0, 100), (150, 220), (500, 1000)]

Bisect.insort_right (A, (250,400))
Bisect.insort_right (A, (399, 450))
Print a # [(0, 100), (150, 220), (250, 400), (500, 1000)]

Print Bisect.bisect (A, (550, 1200)) # 5

Bisect (sequence, item) => Index Returns the insertion point where the element should be, but the sequence is not modified.

Copy Code code as follows:

Import bisect

A = [(0, 100), (150, 220), (500, 1000)]

Bisect.insort_right (A, (250,400))
Bisect.insort_right (A, (399, 450))
Print a # [(0, 100), (150, 220), (250, 400), (500, 1000)]

Print Bisect.bisect (A, (550, 1200)) # 5
Bisect.insort_right (A, (550, 1200))
Print a # [(0, 100), (150, 220), (250, 400), (399, 450), (500, 1000), (550, 1200)]

The new element is inserted into the 5th position.

5. Weakref

The Weakref module can help us create Python references without blocking the object's destruction operations. This section contains the basic usage of weak reference and introduces a proxy class.

Before we begin, we need to understand what strong reference is. Strong reference is a pointer to the number of references to an object, the lifecycle, and the timing of the destruction. Strong reference, as you can see, is when you assign an object to a variable:

Copy Code code as follows:

>>> a = [1,2,3]
>>> B = A

In this case, the list has two strong reference, respectively, A and B. The list will not be destroyed until both of these references are released.

Copy Code code as follows:

Class Foo (object):
def __init__ (self):
Self.obj = None
print ' Created '

def __del__ (self):
print ' destroyed '

Def show (self):
Print Self.obj

def store (self, obj):
Self.obj = obj

A = Foo () # Created
b = A
Del A
Del B # destroyed

Weak Reference is a reference counter to an object that does not have an impact. When an object exists weak reference, it does not affect the object's revocation. This means that if an object is left with only weak reference, then it will be destroyed.

You can use the WEAKREF.REF function to create an object's weak reference. This function call needs to pass a strong reference as the first argument to the function and return a weak reference.

Copy Code code as follows:

>>> Import Weakref
>>> a = Foo ()
Created
>>> B = Weakref.ref (a)
>>> b

A temporary strong reference can be created from the weak reference, which is B () in the following example:

Copy Code code as follows:

>>> a = B ()
True
>>> b (). Show ()
None

Please note that when we delete the strong reference, the object will be destroyed immediately.

Copy Code code as follows:

>>> del A
Destroyed

If you attempt to use an object through weak reference after the object is destroyed, none is returned:

Copy Code code as follows:

>>> B () is None
True

If you use Weakref.proxy, you can provide more transparent optional operations relative to Weakref.ref. It also uses a strong reference as the first argument and returns a weak reference,proxy more like a strong reference, but throws an exception when the object does not exist.

Copy Code code as follows:

>>> a = Foo ()
Created
>>> B = Weakref.proxy (a)
>>> b.store (' Fish ')
>>> B.show ()
Fish
>>> del A
Destroyed
>>> B.show ()
Traceback (most recent call last):
File "", Line 1, in?
Referenceerror:weakly-referenced object no longer exists

Complete Example:
Reference counters are used by the Python garbage collector, and when an object's application counter becomes 0, it is reclaimed by the garbage collector.

It is a good idea to use weak reference for expensive objects or to avoid circular references (although the garbage collector often does this).

Copy Code code as follows:

Import Weakref
Import GC

Class MyObject (object):
def my_method (self):
print ' My_method was called! '

obj = MyObject ()
r = weakref.ref (obj)

Gc.collect ()
Assert R () is obj #r () allows to access the object Referenced:it ' s there.

obj = 1 #Let ' s change what obj references to
Gc.collect ()
Assert R () is None #There are no object Left:it was GC ' ed.

Tip: Only class instances, functions, methods, sets, frozen sets, files, generators, type objects, and certain object defined in the library module Types (for example, sockets, arrays, and regular expression patterns) support Weakref. Built-in functions and most of the built-in types such as lists, dictionaries, strings, and numbers are not supported.

6. Copy ()

Provides function operations for replicated objects through shallow or deep copy syntax.

The difference between shallow and deep copying is the manipulation of mixed objects (objects that contain other types of objects, such as list or other class instances).

1. For shallow copy, it creates a new mixed object and inserts references from other objects in the original object into the new object.
2. For deep copy, it creates a new object and recursively duplicates the other objects in the source object and inserts the new object.

Ordinary assignment operation knowledge simply points the heart variable to the source object.

Copy Code code as follows:

Import Copy

A = [1,2,3]
b = [4,5]

c = [A,b]

# Normal Assignment
D = C

Print ID (c) = = ID (d) # true-d is the same object as C
Print ID (c[0]) = = ID (d[0]) # True-d[0] is the same object as C[0]

# Shallow Copy
D = copy.copy (c)

Print ID (c) = = ID (d) # false-d is now a new object
Print ID (c[0]) = = ID (d[0]) # True-d[0] is the same object as C[0]

# Deep Copy
D = copy.deepcopy (c)

Print ID (c) = = ID (d) # false-d is now a new object
Print ID (c[0]) = = ID (d[0]) # False-d[0] is now a new object

The shallow copy () action creates a new container that contains references to objects in the original object.

The object created by deep copy (Deepcopy ()) contains references to new objects that are copied.

A complex example:

Assuming I have two classes called manager and graph, each graph contains a reference to its manager, and each manager has a collection of graph points to manage, now we have two tasks to complete:

1 copy a graph instance and use Deepcopy, but its manager points to the manager of the original graph.

2 Copy a manager, completely create a new manager, but copy all of the original graph.

Copy Code code as follows:



Import weakref, copy





Class Graph (object):


def __init__ (self, Manager=none):


Self.manager = None If Manager is none else Weakref.ref (manager)


def __deepcopy__ (self, memodict):


Manager = Self.manager ()


Return Graph (Memodict.get (ID (manager), manager))





Class Manager (object):


def __init__ (self, graphs=[]):


Self.graphs = graphs


For G in Self.graphs:


G.manager = Weakref.ref (self)





A = Manager ([Graph (), graph ()])


b = Copy.deepcopy (a)





if [G.manager () is B to G in b.graphs]:


Print true # True





If Copy.deepcopy (A.graphs[0]). Manager () is a:


Print true # True


7. Pprint ()

The Pprint module provides a more elegant way to print data structures, and if you need to print a more complex, deeper-layered dictionary or JSON object, use Pprint to provide better print results.

Suppose you need to print a matrix, when you use normal print, you can only print out a normal list, but if you use Pprint, you can play a pretty matrix structure.

If

Copy Code code as follows:

Import Pprint

Matrix = [[1,2,3], [4,5,6], [7,8,9]]
A = Pprint. Prettyprinter (WIDTH=20)
A.pprint (Matrix)

# [[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]

The extra knowledge

Some of the basic data structures

1. Single Chain list

Copy Code code as follows:



Class Node:


def __init__ (self):


Self.data = None


Self.nextnode = None





def set_and_return_next (self):


Self.nextnode = Node ()


Return Self.nextnode





def getNext (self):


Return Self.nextnode





def getData (self):


Return Self.data





def setData (self, D):


Self.data = d





Class LinkedList:


def buildlist (self, Array):


Self.head = Node ()


Self.head.setData (Array[0])


Self.temp = Self.head


For i in Array[1:]:


Self.temp = Self.temp.set_and_return_Next ()


Self.temp.setData (i)


Self.tail = Self.temp


Return Self.head


def printlist (self):


Tempnode = Self.head


while (Tempnode!=self.tail):


Print (Tempnode.getdata ())


Tempnode = Tempnode.getnext ()


Print (Self.tail.getData ())


MyArray = [3, 5, 4, 6, 2, 6, 7, 8, 9, 10, 21]





MyList = LinkedList ()


Mylist.buildlist (myarray)


Mylist.printlist ()


2. Plim algorithm implemented in Python

Translator Note: The Plim algorithm (prims algorithm) is an algorithm for searching the minimum spanning tree in a weighted connected graph in graph theory.

Copy Code code as follows:



From collections Import Defaultdict


From HEAPQ import heapify, Heappop, Heappush





Def prim (nodes, edges):


conn = defaultdict (list)


For n1,n2,c in edges:


conn[N1].append ((c, N1, N2))


conn[n2].append ((C, N2, N1))





MST = []


Used = Set (nodes[0])


Usable_edges = conn[Nodes[0] [:]


Heapify (Usable_edges)





While Usable_edges:


Cost, n1, N2 = Heappop (usable_edges)


If N2 not in used:


Used.add (N2)


Mst.append ((N1, N2, cost)





For e in conn[N2]:


If e[2] not in used:


Heappush (Usable_edges, E)


Return MST





#test


nodes = List ("ABCDEFG")


edges = [("A", "B", 7), ("A", "D", 5),


("B", "C", 8), ("B", "D", 9), ("B", "E", 7),


("C", "E", 5),


("D", "E",), ("D", "F", 6),


("E", "F", 8), ("E", "G", 9),


("F", "G", 11)]





Print "Prim:", prim (nodes, edges)


Summarize

If you want to know more about data structure information, refer to the documentation. Thanks for reading.

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.