[英]An elegant way of finding the closest value in a circular ordered list
給定一個排序列表,如[1.1, 2.2, 3.3]
math.pi*2
[1.1, 2.2, 3.3]
和一個邊界值,如math.pi*2
,返回[0 - math.pi*2)
任何給定值的最接近值
該函數應該返回值的索引,因此f(1.2)
返回0
而f(2.1)
返回1
,而f(6.0)
應該在math.pi*2
處math.pi*2
並返回0
,更接近於1.1而不是3.3給出邊界值。 為了完全明確,這個函數也應該在下端f(1.0, [5.0, 6.0], bound = math.pi*2)
,這樣f(1.0, [5.0, 6.0], bound = math.pi*2)
返回1
。
用例是將弧度的任意角度映射到列表中最近的現有有效角度。 我在python中用bisect
寫了幾次這樣的函數,但代碼總是冒犯我的審美意識。 邊緣情況的高復雜性和數量似乎與功能的直觀簡單性不成比例。 所以我想問一下,無論是在效率還是優雅方面,是否有人都能提出令人滿意的實施方案。
這是一種更優雅的方法。 通過包裹數字線來消除邊緣情況:
from bisect import bisect_right
def circular_search(points, bound, value):
##
## normalize / sort input points to [0, bound)
points = sorted(list(set([i % bound for i in points])))
##
## normalize search value to [0, bound)
value %= bound
##
## wrap the circle left and right
ext_points = [i-bound for i in points] + points + [i+bound for i in points]
##
## identify the "nearest not less than" point; no
## edge cases since points always exist above & below
index = bisect_right(ext_points, value)
##
## choose the nearest point; will always be either the
## index found by bisection, or the next-lower index
if abs(ext_points[index]-value) >= abs(ext_points[index-1]-value):
index -= 1
##
## map index to [0, npoints)
index %= len(points)
##
## done
return points[index]
正如所寫的那樣,除非輸入像沒有點,或者綁定== 0,否則它們會工作。
使用bisect
模塊作為基礎:
from bisect import bisect_left
import math
def f(value, sorted_list, bound=math.pi * 2):
value %= bound
index = bisect_left(sorted_list, value)
if index == 0 or index == len(sorted_list):
return min((abs(bound + sorted_list[0] - value), 0), (abs(sorted_list[-1] - value), len(sorted_list) - 1))[1]
return min((index - 1, index),
key=lambda i: abs(sorted_list[i] - value) if i >= 0 else float('inf'))
演示:
>>> sorted_list = [1.1, 2.2, 3.3]
>>> f(1.2, sorted_list)
0
>>> f(2.1, sorted_list)
1
>>> f(6.0, sorted_list)
0
>>> f(5.0, sorted_list)
2
最簡單的方法就是使用min:
def angular_distance(theta_1, theta_2, mod=2*math.pi):
difference = abs(theta_1 % mod - theta_2 % mod)
return min(difference, mod - difference)
def nearest_angle(L, theta):
return min(L, key=lambda theta_1: angular_distance(theta, theta_2))
In [11]: min(L, key=lambda theta: angular_distance(theta, 1))
Out[11]: 1.1
利用列表的排序,您可以使用bisect模塊:
from bisect import bisect_left
def nearest_angle_b(theta, sorted_list, mod=2*math.pi):
i1 = bisect_left(sorted_list, theta % mod)
if i1 == 0:
i1, i2 = len(sorted_list) - 1, 0
elif i1 == len(sorted_list):
i1, i2 = i1 - 1, 0
else:
i2 = (i1 + 1) % len(sorted_list)
return min((angular_distance(theta, L[i], mod), i, L[i])
for i in [i1, i2])
返回列表中距離最近的距離,索引和角度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.