从IP地址范围获取城市
- 我有一个IP地址。例如,192.168.2.10
- 我还有一本字典:
RANGES = {
'london': [
{'start': '10.10.0.0', 'end': '10.10.255.255'},
{'start': '192.168.1.0', 'end': '192.168.1.255'},
],
'munich': [
{'start': '10.12.0.0', 'end': '10.12.255.255'},
{'start': '172.16.10.0', 'end': '172.16.11.255'},
{'start': '192.168.2.0', 'end': '192.168.2.255'},
]
}
问题:我应该如何从我的IP地址找到城市并使用这本字典花费尽可能少的时间(时间复杂度)?
- I have an IP address. For example, 192.168.2.10
- Also I have a dictionary:
RANGES = {
'london': [
{'start': '10.10.0.0', 'end': '10.10.255.255'},
{'start': '192.168.1.0', 'end': '192.168.1.255'},
],
'munich': [
{'start': '10.12.0.0', 'end': '10.12.255.255'},
{'start': '172.16.10.0', 'end': '172.16.11.255'},
{'start': '192.168.2.0', 'end': '192.168.2.255'},
]
}
Question: How should I find the city from my IP address and use this dictionary spending less time (time complexity) as possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想要任意大数据集的最佳复杂性,“正确的答案”就是季斌给出的答案。
要真正优化多次调用的性能,您确实需要重组数据并使用内置的二等分函数。
但如果你真的不想碰你的数据,你仍然可以使用 bisect 的创可贴自定义实现,它看起来像这样
->无
->慕尼黑
->伦敦
->无
->慕尼黑
->伦敦
等
游乐场链接:https://trinket.io/python/e1f9deb1c7
The "proper answer" if you want the best complexity for arbitrarily large data sets is the one given given by Ji Bin.
To really optimize performances over multiple calls, you indeed need to restructure your data, and use the inbuilt bisect function.
But if you REALLY do not want to touch your data, you can still use a band-aid custom implementation of bisect which would look like that
-> None
-> munich
-> london
-> None
-> munich
-> london
etc.
link to playground : https://trinket.io/python/e1f9deb1c7
编写一个自定义函数,将 IP 地址解析为数字元组,以便于比较:
Write a custom function which parses the IP addresses as tuples of numbers for easier comparison:
首先,您需要重新排列数据,以便更有效地查找。
现在,您可以使用 bisect 搜索排序后的起始 IP,对于您的输入,在内部使用 RB 树进行 AIK。
下面是完整的 PoC 代码:
First, you need to rearrange your data, for lookup more efficiently.
Now, you could use
bisect
to search the sorted start IP, for your input, AIK it using the RB-tree internally.Below is the whole PoC code for it: