Find the minimum range that includes all angles in the list.

I have a list of sorted values ​​representing angles (in degrees), all in the range [0,360)

My goal is to find the best range (minimum range) that matches all corners in the list.

Some examples:

  • Given a list of angles = [0,1,2,10,20,35] , the answer will be (0,35) .

  • Given the list angles = [10,20,340,355] , due to the circular nature of the values, the answer will be (340,20) .

My current script works as follows:

 MAX_ANGLE = 360 def get_best_range(angles): number_of_angles = len(angles) # Append the list of angles with the same angles plus 360 (max value) angles = angles + [angle + MAX_ANGLE for angle in angles] # Create a list of all possible ranges possible_ranges = [(angles[i], angles[i+number_of_angles - 1]) for i in range(number_of_angles)] # Find the best range (minimum range) best_range = min(possible_ranges, key = lambda ang_range: ang_range[1] - ang_range[0]) return best_range[0], best_range[1]%MAX_ANGLE 

Ok, this is my best approach so far, and it works in O (n), which is good, but it seems to me that in python there may be a better way to do this. Maybe some kind of tool for working with circular values? I always have a bit of trouble when working with corners or other circular values.

+5
source share
2 answers

This liner should do the trick:

 max(zip(angles, angles[1:] + [360+angles[0]]), key = lambda x: x[1]-x[0]) 

(later you can change the answer to values ​​less than 360)

+3
source
  def f(my_list): maxi = max(my_list) mini = min(my_list) if maxi - mini < 180: return (mini, maxi) else: return (min([x for x in my_list if x >= 180]), max([x for x in my_list if x<180])) 
0
source

Source: https://habr.com/ru/post/1267148/


All Articles