Guide to using the binary tree search algorithm module in Python

Source: Internet
Author: User
Tags pop value
Binary Tree search algorithms are often used in development practices. By convention, Python will certainly provide a wheel for such a common thing. Yes, this is the case with python, which will save developers effort and reduce developers' work pressure. Binary Tree module in python:

BinaryTree: non-balanced binary tree
AVLTree: balanced AVL tree
RBTree: balanced red/black tree
The above is written in python, and the phase module is written in c and can be used as a Cython package.

FastBinaryTree
FastAVLTree
FastRBTree
Note that the tree is often slower than the built-in dict class in python, but all the data in the tree is sorted by a keyword, therefore, it must be used in some cases.

Installation and Use

Installation method

Installation environment:

Ubuntu12.04, python 2.7.6

Installation method

Download source code, address: https://bitbucket.org/mozman/bintrees/src
Go to the source code directory and see the setup. py file, which runs

python setup.py install

Installation successful, OK! The following describes how to use it.

Application

Bintrees provides a variety of APIs, covering a variety of common applications. The following sections describe their applications one by one.

-Reference

If you follow the general idea of the module, enter the following command to introduce the above module

>>> import bintrees


Wrong. this is wrong. the following warning is displayed: (××× unavailable, ×××)

  Warning: FastBinaryTree not available, using Python version BinaryTree.  Warning: FastAVLTree not available, using Python version AVLTree.  Warning: FastRBTree not available, using Python version RBTree.

The correct introduction method is:

>>> From bintrees import BinaryTree # only BinartTree is introduced >>> from bintrees import * # all three modules are introduced

-Instantiation

Example:

>>> btree = BinaryTree()  >>> btree  BinaryTree({})  >>> type(btree)  
 


-Add key-value pairs one by one :. _ setitem _ (k, v ). complexity O (log (n) (in subsequent instructions, there will be a complexity mark. for simplicity, it is directly marked as O (log (n )).)

Example:

>>> btree.__setitem__("Tom","headmaster") >>> btree BinaryTree({'Tom': 'headmaster'}) >>> btree.__setitem__("blog","http://blog.csdn.net/qiwsir") >>> btree BinaryTree({'Tom': 'headmaster', 'blog': 'http://blog.csdn.net/qiwsir'})


-Batch Add:. update (E) E is dict/iterable, and E is updated to btree. O (E * log (n) in batches ))

Example:

>>> adict = [(2,"phone"),(5,"tea"),(9,"scree"),(7,"computer")]  >>> btree.update(adict)  >>> btree  BinaryTree({2: 'phone', 5: 'tea', 7: 'computer', 9: 'scree', 'Tom': 'headmaster', 'blog': 'http://blog.csdn.net/qiwsir'})


-Check whether a key exists:. _ contains _ (k) if the key k exists, True is returned; otherwise, False. O (log (n) is returned ))

Example:

>>> btree BinaryTree({2: 'phone', 5: 'tea', 7: 'computer', 9: 'scree', 'Tom': 'headmaster', 'blog': 'http://blog.csdn.net/qiwsir'}) >>> btree.__contains__(5) True >>> btree.__contains__("blog") True >>> btree.__contains__("qiwsir") False >>> btree.__contains__(1) False


-Delete a key-value according to the key:. _ delitem _ (key), O (log (n ))

Example:

>>> Btree BinaryTree ({2: 'phone', 5: 'Tea ', 7: 'computer', 9: 'scree ', 'Tom': 'headmaster ', 'blog ': 'http: // blog.csdn.net/qiwsir'}) >>> btree. _ delitem _ (5) # Delete the key-value of key = 5, that is, 5: 'Tea 'is deleted. >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'Tom ': 'headmaster', 'blog': 'http: // blog.csdn.net/qiwsir '})

-Calculate the value of kye according to the key:. _ getitem _ (key)

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'Tom ': 'headmaster', 'blog': 'http: // blog.csdn.net/qiwsir'}) >>> btree. _ getitem _ ("blog") 'http: // blog.csdn.net/qiwsir' >>> btree. _ getitem _ (7) 'computer '> btree. _ getitem _ (5) # no key = 5 in B tree, so an error is returned. Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
AttributeError: 'binarytree' object has no attribute' _ getitem __'
  
 

-Iterator:. _ iter __()

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'Tom ': 'headmaster', 'blog': 'http: // blog.csdn.net/qiwsir'}) >>> aiter = btree. _ iter _ () >>> aiter
 
  
At 0xb7416dec >>>> aiter. next () # Note: After next (), this value is deleted from the list. 2 >>> aiter. next () 7 >>> list (aiter) [9, 'Tom ', 'blog'] >>> list (aiter) # The result is null [] >>> bool (aiter) # but, is True
 

-Tree data length:. _ len _ (), returns the length of B-tree. O (1)

Example:

>>> btree  BinaryTree({2: 'phone', 7: 'computer', 9: 'scree', 'Tom': 'headmaster', 'blog': 'http://blog.csdn.net/qiwsir'})  >>> btree.__len__()  5

-Find the maximum key-value pair:. _ max _ (). sort the key and return the maximum key-value pair.


-Find the smallest key-value pair of the key:. _ min __()

Example:

>>> btree BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'}) >>> btree.__max__() (9, 'scree') >>> btree.__min__() (2, 'phone')

-Two-digit relational operation

Example:

>>> Other = [(3, 'http: // www.jb51.net'), (7, 'qiwsir ')] >>> bother = BinaryTree () # create another tree> bother. update (other) # Add data >>> bother BinaryTree ({3: 'http: // www.jb51.net ', 7: 'qiwsir'}) >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree'}) >>> btree. _ and _ (bother) # BinaryTree ({7: 'computer '})> btree. _ or _ (bother) # All BinaryTree ({2: 'phone', 3: 'http: // www.jb51.net, 7: 'computer ', 9: 'scree '}) >>> btree. _ sub _ (bother) # BinaryTree ({2: 'phone', 9: 'scree '}) that does not overlap with bother> btree. _ xor _ (bother) # BinaryTree ({2: 'phone', 3: 'http: // www.jb51.net, 9: 'scree '})

-Output string format:. _ repr __()

Example:

>>> btree  BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})  >>> btree.__repr__()  "BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})"

-Clear all data in the tree:. clear (), O (log (n ))

Example:

>>> bother   BinaryTree({3: 'http://blog.csdn.net/qiwsir', 7: 'qiwsir'}) >>> bother.clear() >>> bother BinaryTree({}) >>> bool(bother) False

-Shallow copy:. copy (). It is a brief copy in the official document, but I have implemented it as shown below. it does not quite understand its meaning. O (n * log (n ))

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree'}) >>> ctree = btree. copy () >>> ctree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree'}) >>> btree. _ setitem _ ("github", "qiwsir") # Add btree data >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree ', 'github': 'qiwsir '}) >>> ctree BinaryTree ({2: 'phone', 7: 'computer', 9: 'scree '}) # Is this a deep copy? >>> Ctree. _ delitem _ (7) # delete a ctree data >>> ctree BinaryTree ({2: 'phone', 9: 'scree '}) >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir '})

-Remove a data in the tree:. discard (key). This function is similar to. _ delitem _ (key). both of them have no regrets. O (log (n ))

Example:

>>> Ctree BinaryTree ({2: 'phone', 9: 'scree '}) >>> ctree. discard (2) # No Return value after deletion, or return None >>> ctree BinaryTree ({9: 'scree '}) >>> ctree. discard (2) # if the deleted key does not exist, return None >>> ctree. discard (3) >>> ctree. _ delitem _ (3) # however ,. _ delitem _ (key) is different. if the key does not exist, an error is returned. Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
File "/usr/local/lib/python2.7/site-packages/bintrees/abctree. py ", line 264, in _ delitem _ self. remove (key) File "/usr/local/lib/python2.7/site-packages/bintrees/bintree. py ", line 124, in remove raise KeyError (str (key) KeyError: '3'
  
 

-Search by key, and return or return the alternate value:. get (key [, d]). If the key exists in the tree, value is returned; otherwise, d is returned. O (log (n ))

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir'}) >>> btree. get (2, "algorithm") 'phone'> btree. get ("python", "algorithm") # if no key = 'Python' value exists, 'Algorithm ''' algorithm '>>>> btree. get ("python") # if the second parameter is not specified, if no result is found, None is returned >>>

-Determine whether the tree is empty: is_empty (). based on the length of the tree data, if the data length is 0, it is null. O (1)

Example:

>>> Ctree BinaryTree ({9: 'scree '}) >>> ctree. clear () # clear data >>> ctree BinaryTree ({}) >>> ctree. is_empty () True >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir '}) >>> btree. is_empty () False

-Cyclically fetch values from the tree based on the key and value:

>>. Items ([reverse]) -- values are structured according to (key, value;

>. Keys ([reverse]) -- key

>. Values ([reverse]) -- value. O (n)

>. Iter_items (s, e [, reverse] -- s, e is the key range, that is, the iterator O (n) that generates the key within a range)

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir'}) >>> for (k, v) in btree. items ():... print k, v... 2 phone 7 computer 9 scree github qiwsir >>> for k in btree. keys ():... print k... 2 7 9 github >>> for v in btree. values ():... print v... phone computer scree qiwsir >>> for (k, v) in btree. items (reverse = True): # reverse order... print k, v... github qiwsir 9 scree 7 computer 2 phone >>> btree BinaryTree ({2: 'phone', 5: None, 7: 'computer ', 8: 'Eight', 9: 'scree ', 'github': 'qiwsir '}) >>> for (k, v) in btree. iter_items (6, 9): # key-value pairs requiring iteration of 6 <= key <9... print k, v... 7 computer 8 eight >>>

-Delete the data and return the value:

>. Pop (key [, d]): deletes the data in the tree based on the key and returns the value. If no value exists and the alternative d is specified, the return d is returned, if no d exists, an error is returned;

>>. Pop_item (), randomly select (key, value) in the tree to delete and return.

Example:

>>> Ctree = btree. copy () >>> ctree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir'}) >>> ctree. pop (2) # delete the data whose key is 2 and return its value 'phone' >>> ctree. pop (2) # delete a key that does not exist. the error Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
File "/usr/local/lib/python2.7/site-packages/bintrees/abctree. py ", line 350, in pop value = self. get_value (key) File "/usr/local/lib/python2.7/site-packages/bintrees/abctree. py ", line 557, in get_value raise KeyError (str (key) KeyError: '2' >>> ctree. pop_item () # A random (key, value) is returned and deleted (7, 'computer ') >>> ctree BinaryTree ({9: 'scree', 'github ': 'qiwsir '}) >>> ctree. pop (7, "sing") # if not, you can return the specified value 'sing'
  
 

-Search for data and return value:. set_default (key [, d]). find the key in the data in the tree. If yes, return the value. If d does not exist, add (key, d) to the tree if d is specified. if d is not specified, add (key, None ). O (log (n ))

Example:

>>> Btree BinaryTree ({2: 'phone', 7: 'computer ', 9: 'scree', 'github ': 'qiwsir'}) >>> btree. set_default (7) # If yes, the return value is 'computer '> btree. set_default (8, "eight") # if no value exists, the backup value is returned and added to the 'Eight '>>> btree BinaryTree ({2: 'phone', 7: 'computer ', 8: 'Eight', 9: 'scree ', 'github': 'qiwsir '}) >>> btree. set_default (5) # if no value is specified, None> btree BinaryTree ({2: 'phone', 5: None, 7: 'computer ', 8: 'eight ', 9: 'scree', 'github ': 'qiwsir'}) >>> btree. get (2) # note ,. get (key) and. set_default (key [, d]) difference 'phone' >>> btree. get (3, "mobile") # key that does not exist. it is returned but is not added to the 'mobile' tree. >>> btree BinaryTree ({2: 'phone', 7: 'computer ', 8: 'Eight ', 9: 'scree', 'github ': 'qiwsir '})

-Delete value based on key

>. Remove (key), delete (key, value)

>. Remove_items (keys). keys is a list composed of keys, which deletes the corresponding data in the tree one by one.

Example:

>>> Ctree BinaryTree ({2: 'phone', 5: None, 7: 'computer ', 8: 'Eight', 9: 'scree ', 'github ': 'qiwsir '}) >>> ctree. remove_items ([5, 6]) # key = 6, does not exist, error Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
File "/usr/local/lib/python2.7/site-packages/bintrees/abctree. py ", line 271, in remove_items self. remove (key) File "/usr/local/lib/python2.7/site-packages/bintrees/bintree. py ", line 124, in remove raise KeyError (str (key) KeyError: '6' >>> ctree BinaryTree ({2: 'phone', 7: 'computer ', 8: 'Eight ', 9: 'scree', 'github ': 'qiwsir'}) >>> ctree. remove_items ([, 'github ']) # delete one by one in the order listed> ctree BinaryTree ({8: 'Eight', 9: 'scree '})
  
 


# The above is just the basic method for getting started. For more information, please do not go to the official website starting with the article

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.