Python two-tree lookup algorithm Module usage guide

Source: Internet
Author: User
Tags true true
The contents of the two-fork tree module in Python:

BinaryTree: Unbalanced binary tree
Avltree: The Balanced AVL tree
Rbtree: Balanced red-black tree
The above is written in Python, the face Reading module is written in C, and can be used as a Cython package.

Fastbinarytree
Fastavltree
Fastrbtree
It is important to note that trees tend to be slower than Python's built-in dict classes, but all of the data in it is sorted by a keyword, so 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 directory, see the setup.py file, run it inside the directory

Python setup.py Install

The installation is successful, ok! below to see how to use.

Application

Bintrees provides a rich API that covers a wide variety of applications. The following article describes its application.

-Reference

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

>>> Import Bintrees


Wrong, this is wrong, the following warning appears: (XXX is not available, with XXX)

  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 right way to introduce this is:

  >>> from bintrees import BinaryTree   #只引入了BinartTree  >>> from bintrees import *       #三个模块都引入了

-Instancing

See Example:

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


-Increment the key-value pair:. __setitem__ (k,v). Complexity O (log (n)) (follow-up instructions will have a complexity indicator, for simple, direct indication: O (log (n)).)

See 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 '})


-Bulk add:. Update (E) e is dict/iterable, and E is updated in bulk to Btree. O (E*log (n))

See 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://b Log.csdn.net/qiwsir '})


-Find out if a key exists:. __contains__ (k) Returns True if there is a key k, otherwise false. O (log (n))

See 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 key:. __delitem__ (Key), O (log (n))

See Example:

>>> btree  BinaryTree ({2: ' Phone ', 5: ' Tea ', 7: ' Computer ', 9: ' scree ', ' Tom ': ' Headmaster ', ' blog ': ' http://b Log.csdn.net/qiwsir '})  >>> btree.__delitem__ (5)    #删除key The key-value of =5, i.e.: 5: ' Tea ' was deleted.  >>> btree  BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' Tom ': ' Headmaster ', ' blog ': ' Http://blog.csdn . Net/qiwsir '})

-Gets the value of the Kye according to the key value:. __getitem__ (Key)

See 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)  #在btree中没有key = 5, then error. Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
    attributeerror: ' BinaryTree ' object has No attribute ' _getitem__ '
  
   
 
  

-iterators:. __iter__ ()

See 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 () #注意: Next () after one, the value is removed from List 2 >>> aiter.next () 7 >>> list (aiter) [9, ' Tom ', ' blog '] >>> list (aiter)  #结果是空 [] >>> bool (aiter)  #but, is true true
 
  

-Tree data length:. __LEN__ (), returns the length of the btree. O (1)

See Example:

>>> btree  BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' Tom ': ' Headmaster ', ' blog ': ' Http://blog.csdn . Net/qiwsir '})  >>> btree.__len__ ()  5

-Find out key max K-v pairs:. __max__ (), in the key order, return key key value pair.


-Find key to the minimum value pair:. __min__ ()

See Example:

>>> Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree '}) >>> btree.__max__ () (9, ' scree ') >>& Gt Btree.__min__ () (2, ' phone ')

-Relational operations of two trees

See Example:

>>> other = [(3, ' http://www.jb51.net '), (7, ' Qiwsir ')] >>> bother = BinaryTree ()  #再建一个树 >> > Bother.update (Other) #加入数据 >>> 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) #全部 BinaryTree ({2: ' Phone ', 3: ' Http://www.jb51.net, 7: ' Computer ', 9: ' scree '}) >>> btree.__sub__ (bother)  #btree不与bother重叠的部分 BinaryTree ({2: ' phone ', 9: ' Scree '} )  >>> btree.__xor__ (bother)  #两者非重叠部分 BinaryTree ({2: ' Phone ', 3: ' Http://www.jb51.net, 9: ' Scree '})

-Output string appearance, note only the appearance of the output:. __REPR__ ()

See Example:

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

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

See Example:

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

-Shallow copy:. Copy (), the official document is a shallow copy, but I did the operation implementation, is shown below, still do not understand its "shallow" meaning. O (N*log (n))

See Example:

>>> Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree '}) >>> ctree = btree.copy () >>> ctre E BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree '}) >>> btree.__setitem__ ("GitHub", "Qiwsir") #增加btree的数据 > >> Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) >>> Ctree BinaryTree ({2: ' Phone ', 7: ' Computer ', 9: ' scree '}) #这是不是在说明属于深拷贝呢?  >>> ctree.__delitem__ (7) #删除ctree的一个数据 >>> Ctree BinaryTree ({2: ' phone ', 9: ' scree '}) >> > Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir '})

-Remove one of the data from the tree:. Discard (key), which is similar to. __delitem__ (key). Both do not regret the value. O (log (n))

See Example:

>>> Ctree BinaryTree ({2: ' phone ', 9: ' scree ') >>> Ctree.discard (2) #删除后, does not return a value, or returns none >>> Ctree BinaryTree ({9: ' scree '}) >>> Ctree.discard (2) #如果删除的key不存在, also returns none >>> Ctree.discard (3) > >> ctree.__delitem__ (3) #但是,. __delitem__ (key) is different, if the key does not exist, will be an error. Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
     file "/usr/local/lib/python2.7/ site-packages/bintrees/abctree.py ", line, 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 '
  
   
 
  

-Finds by key and returns or returns an alternate value:. Get (Key[,d]). If the key exists in the tree, it returns value, or if there is D, the D value is returned. O (log (n))

See Example:

>>> Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) >>> Btree.get (2, "Algo Rithm ") ' Phone ' >>> btree.get (" Python "," algorithm ") #没有key = ' python ' value, return ' algorithm ' algorithm ' >> > btree.get ("Python") #如果不指定第二个参数, if not found, returns none >>>

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

See Example:

>>> Ctree BinaryTree ({9: ' scree '}) >>> ctree.clear ()  #清空数据 >>> ctree BinaryTree ({}) > >> ctree.is_empty () True >>> btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) >>> Btree.is_empty () False

-values are taken from the tree according to the key, value loop:

>>.items ([reverse])--Value according to (KEY,VALUE) structure;

>>.keys ([reverse])--key

>>.values ([reverse])--value. O (N)

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

See 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 B  Tree.items (reverse=true): #反序 ... 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): #要求迭代6 <=key<9 Key-value pair data ... print k,v ... 7 Computer 8 Eight >>>

-delete the data and return the value:

>>.pop (Key[,d]), delete the tree data according to key, and return the value, but if not, and also specify the alternative returned d, then return D, if not d, then error;

>>.pop_item (), randomly selected in the tree (Key,value) is deleted and returned.

See Example:

>>> ctree = btree.copy () >>> ctree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir ') }) >>> Ctree.pop (2) #删除key =2 data, return its value ' phone ' >>> ctree.pop (2) #删除一个不存在的key, error Traceback (most Recent call last):  file "
 
  
   
  ", line 1, in 
  
   
    
     file "/usr/local/lib/python2.7/site-packages/ bintrees/abctree.py ", line A, 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 ()  #随机返回一个 (Key,value) and deleted (7, ' computer ') >>> Ctree BinaryTree ({9: ' scree ', ' GitHub ': ' Qiwsir '})  >>> Ctree.pop (7, "sing") #如果没有, can return the specified value ' Sing
  '
   
 
  

-Finds the data and returns the value:. Set_default (Key[,d]), finds the key in the tree's data, and returns the value if it exists. If not present, when D is specified, the (key,d) is added to the tree and (Key,none) is added when no d is specified. O (log (n))

See Example:

>>> Btree BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) >>> Btree.set_default (7) #存在则返回 ' computer '  >>> btree.set_default (8, "eight") #不存在, return the reserved specified value and add to the tree ' eight ' >>> btree BinaryTree ({2: ' phone ', 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '})  >>> Btree.set_default (5 ) #如果不指定值 will join None >>> btree BinaryTree ({2: ' phone ', 5:none, 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Q Iwsir '}) >>> Btree.get (2) #注意, the difference between. Get (key) and. Set_default (Key[,d]) ' Phone ' >>> btree.get (3, "mobile")  #不存在的 key, return but not add to tree ' mobile ' >>> btree BinaryTree ({2: ' phone ', 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '})

-delete values based on key

>>.remove (key), delete (Key,value)

>>.remove_items (keys), keys is a list of keys that delete the corresponding data in the tree

See Example:

>>> Ctree BinaryTree ({2: ' phone ', 5:none, 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) >>&G T Ctree.remove_items ([5,6])  #key = 6, not present, 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 ([2,7, ' GitHub ']) #按照 list in order to delete each >>> Ctree BinaryTree ({8: ' Eight ', 9: ' scree '})
  
   
 
  


# #以上只是入门的基本方法啦 and more, please don't move to the official website at the beginning of the article

  • Related 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.