Two-fork Tree Lookup Algorithm Module usage guide in Python _python

Source: Internet
Author: User
Tags shallow copy stdin in python

Two-fork Tree module contents in Python:

BinaryTree: Non-balanced two-fork tree
Avltree: A balanced AVL tree
Rbtree: A balanced red-black tree
The above is written in Python, and the Physiognomy module is written in C and can be used as a Cython package.

Fastbinarytree
Fastavltree
Fastrbtree
It is particularly important to note that trees tend to be slower than Python-built 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, Address: https://bitbucket.org/mozman/bintrees/src
Access to the source directory, see setup.py file, run in the directory

Python setup.py Install

Installation is successful, ok! below to see how to use.

Application

The bintrees provides a rich API that covers a wide range of common applications. The following article explains its application.

-Reference

If you follow the general modular approach, enter the following command to introduce the above module

>>> Import Bintrees


Wrong, this is wrong, appear the following warning: (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 correct way to introduce it is:

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

-Instantiated

See Example:

>>> btree = BinaryTree ()
  >>> btree
  BinaryTree ({})
  >>> type (btree)
  <class ' Bintrees.bintree.BinaryTree ' >


-Add key value pairs:. __setitem__ (k,v). Complexity O (log (n)) (in subsequent instructions, there will be a complexity indicator, for simplicity, directly labeled: 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, the e batch is updated into 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:// Blog.csdn.net/qiwsir '})


-Find whether a key exists:. __contains__ (k) Returns True if it contains a key k, otherwise returns false. 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.__contains__ (5)
 True
 >>> btree.__contains__ ("blog ")
 True
 >>> btree.__contains__ (" Qiwsir ")
 False
 >>> btree.__contains__ (1)
 False


-delete a key-value from key:. __delitem__ (Key), O (log (n))

See Example:

>>> btree
  BinaryTree ({2: ' Phone ', 5: ' Tea ', 7: ' Computer ', 9: ' scree ', ' Tom ': ' Headmaster ', ' blog ': ' http:// Blog.csdn.net/qiwsir '})
  >>> btree.__delitem__ (5)    #删除key The key-value of =5, that is: 5: ' Tea ' was removed.
  >>> 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, so the error is not correct.
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 attributeerror: ' BinaryTree ' object has no attribute ' _getitem__ '

-iterator:. __ITER__ ()

See Example:

>>> btree 
 BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' Tom ': ' Headmaster ', ' blog ': ' Http://blog.csdn . Net/qiwsir '})
 >>> aiter = btree.__iter__ ()
 >>> aiter
 <generator Object <genexpr > at 0xb7416dec>
 >>> aiter.next () #注意: After Next (), this value is removed from the list
 2
 >>> aiter.next ()
 7
 >>> list (aiter)
 [9, ' Tom ', ' blog ']
 >>> list (aiter)  #结果是空
 []
 >>> bool (aiter)  #but, is true
 

-The length of the tree's data:. __LEN__ (), which 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 the key's largest k-v pair:. __max__ (), sorted by key, returns the key's largest value pair.


-Find key value pairs that are minimal:. __MIN__ ()

See Example:

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

-the relational operation 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) c14/> #btree不与bother重叠的部分
 BinaryTree ({2: ' phone ', 9: ' scree '})
 
 >>> btree.__xor__ (bother)  # Both non-overlapping parts
 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 '})

-Empty 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

-Light copy:. Copy (), the official document says it's a shallow copy, but I did the implementation of the operation, as shown below, not quite understand its "shallow" meaning. O (N*log (n))

See Example:

>>> btree
 BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree '})
 >>> ctree = btree.copy ()
 >>> ctree
 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 in the tree:. Discard (key), which is similar to. __delitem__ (key). Values are not undone. O (log (n))

See Example:

>>> ctree
 BinaryTree ({2: ' phone ', 9: ' scree '})
 >>> Ctree.discard (2) #删除后, do not return a value, or return 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 call last):
  File "<stdin>", line 1, in <module>
  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 '

-Find by key and return or return an alternate value:. Get (Key[,d]). Returns value if the key exists in the tree, otherwise, if D, returns a D value. O (log (n))

See Example:

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

-Determine if the tree is empty: Is_empty (). Based on the length of the tree data, NULL 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 in accordance with (KEY,VALUE) structure;

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

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

>>.iter_items (S,e[,reverse]--s,e is the scope of the key, that is, the iterator O (n) that generates the 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
 . C12/>2
 7
 9
 GitHub
 >>> for V in Btree.values ():
 ... print v.
 Phone
 computer
 scree
 qiwsir
 >>> for (k,v) in Btree.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 the key value of the data
 ... print k,v ...
 7 Computer
 8 eight
 >>>

-Deletes the data and returns the value:

>>.pop (Key[,d]), which deletes the tree's data according to the key and returns the value, but if not, and also specifies the alternative return d, returns D, if there is no d, the error;

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

See Example:

>>> ctree = btree.copy ()
 >>> ctree
 BinaryTree ({2: ' phone ', 7: ' Computer ', 9: ' scree ', ' GitHub ') : ' Qiwsir '}

 >>> Ctree.pop (2) #删除key the =2 data, return its value
 ' phone '
 >>> ctree.pop (2) # Delete a nonexistent key, error
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr" /local/lib/python2.7/site-packages/bintrees/abctree.py ", line, 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 value:. Set_default (Key[,d]), finds the key in the tree's data, and returns the value if it exists. If it does not exist, when D is specified, the (key,d) is added to the tree, and (key,none) is added when D is not 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") #不存在, then return the reserved specified value and add to the tree
 ' Eight '
 >>> btree
 BinaryTree ({2: ' phone ', 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '}) C8/>>>> Btree.set_default (5) #如果不指定值, then add None
 >>> btree
 BinaryTree ({2: ' phone ', 5:none, 7 : ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '} '

 >>> btree.get (2) #注意,. Get (key) and. Set_default ( KEY[,D]) The difference between
 ' phone '
 >>> btree.get (3, "mobile")  #不存在的 key, returns but does not add to the tree
 ' mobile '
 > >> btree
 BinaryTree ({2: ' phone ', 7: ' Computer ', 8: ' Eight ', 9: ' scree ', ' GitHub ': ' Qiwsir '})

-delete value based on key

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

>>.remove_items (keys), keys is a list of key, 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 "<stdin > ", Line 1, in <module>
  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 ']) #按照 Sequential deletion in list
 >>> ctree
 BinaryTree ({8: ' Eight ', 9: ' Scree '})


# #以上只是入门的基本方法啦, there's 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.