Usage example of the bisect module in python

Source: Internet
Author: User
This article mainly introduces the usage examples of the bisect module in python, and introduces the usage of several common functions in the bisect module in the form of examples, which is of great practical value, for more information about how to use the bisect module in python, see the following example.

The specific method is analyzed as follows:

This module has only a few functions. Once you decide to use a binary search, you need to use this module immediately.

The sample code is as follows:

Import bisectL = [1, 3, 6, 8, 12, 15] x = 3x_insert_point = bisect. bisect_left (L, x) # search for x in L. If x exists, the position on the left of x is returned. If x does not exist, the position to be inserted is returned .. this is 3 that exists in the list and returns the position 1 print x_insert_pointx_insert_point = bisect on the left. bisect_right (L, x) # search for x in L. If x exists, the position on the right of x is returned. If x does not exist, the position to be inserted is returned .. this is where 3 exists in the list and returns the right position 3 print x_insert_pointx_insort_left = bisect. insort_left (L, x) # insert x to list L. If x exists, insert it to print lx_insort_ri1_= bisect on the left. insort_right (L, x) # insert x to list L. If x exists, insert it to print L on the right.

In this example, the test environment is Python2.7.6.

The running result is as follows:

13 [1, 3, 3, 3, 6, 8, 12, 15] [1, 3, 3, 3, 3, 6, 8, 12, 15]

In actual use, the difference between bisect. insort_left and bisect. insort_right is not big, and their functions are basically the same.
I hope this article will help you learn Python programming.

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.