MAX = 1_000_000
MIN = 0
target: float = 333_333.0
collection: set[float] = {random.uniform(MIN, MAX) for _ in range(100_000)}
# --- Code here to find closest as fast as possible, now and for future lookups ---
assert closest in collection and all(abs(target - v) >= delta for v in collection)
附录1
with浏览所有值并相应地更新。非常简单,但对于大型收藏而言非常慢。
closest
附录2closest: float = next(iter(collection)) # get any element
delta: float = abs(closest - target)
for v in collection:
tmp_delta = abs(v - target)
if tmp_delta < delta:
closest = v
delta = tmp_delta
附录3
sorted_collection: list[float] = sorted(collection)
idx = bisect.bisect_right(sorted_collection, target)
if idx == 0:
return sorted_collection[0]
if idx == len(sorted_collection):
return sorted_collection[-1]
before, after = sorted_collection[idx - 1], sorted_collection[idx]
return before if target - before <= after - target else after
方法,然后可以使用(装甲)o(1)查找时间来找到值,但是如果没有对所涉及的数据做出一些以前的假设,并且想知道是否有可能。
这是我简而言之。我想知道是否有一种比简单排序 +二进制搜索方法更快的方法,以及我使用dict
+自定义哈希功能的想法是否有可能。
浮子,二进制搜索量表像最著名的量表。但是,它需要在彼此之间在一定距离处查看内存中的位置。 a
b-tree也像
__hash__
一样缩放,但是通过找到彼此接近的决策集,它可以得到一个数量级的恒定改进。哈希想法不起作用,因为良好的哈希功能会以伪随机方式散布附近的值。因此,您没有比搜索整个哈希更好的方法来找到附近的价值观。