Binary Search Using Python and awk

Source: Internet
Author: User

Find the corresponding region code based on the IP address,

The format of the search text content is as follows:

Iparea 22165248 22165503 cn6109
Iparea 22165504 22347775 cn6100
Iparea 22347776 22413311 cn6101
Iparea 22413312 22544383 cn6100
Iparea 22544384 23068671 cn1102
Iparea 24379392 24641535 cn0000
Iparea 27262976 28311551 cn9100
Iparea 28573696 28835839 cn1500
Iparea 28835840 28966911 cn1_1
..............................

Areas_arr stores the dictionary/array of the above text, and its key is the corresponding row number in the text

Awk implementation functions

Def search_newarea (areas_arr, IP, S, e ):
Start = s;
End = E;
IPS = IP. Split (".")
Long_ip = int (IPS [0]) * 256*256*256 + int (IPS [1]) * 256*256 + int (IPS [2]) * 256 + int (IPS [3]);
While (start <= end and start> = s and end <= E ):
Middle = int (start + end)/2 );
Ip_range = areas_arr [Middle]. Split (",")
If (long_ip> = int (ip_range [0]) and long_ip <= int (ip_range [1]):
Return ip_range [2];
If (long_ip> int (ip_range [0]):
Start = middle + 1;
Else:
End = middle-1;
Return '';

Python implementation code

Def search_newarea (areas_arr, IP, S, e ):
Start = s;
End = E;
IPS = IP. Split (".")
Long_ip = int (IPS [0]) * 256*256*256 + int (IPS [1]) * 256*256 + int (IPS [2]) * 256 + int (IPS [3]);
While (start <= end and start> = s and end <= E ):
Middle = int (start + end)/2 );
Ip_range = areas_arr [Middle]. Split (",")
If (long_ip> = int (ip_range [0]) and long_ip <= int (ip_range [1]):
Return ip_range [2];
If (long_ip> int (ip_range [0]):
Start = middle + 1;
Else:
End = middle-1;
Return '';

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.