|
| 1 | +from collections import defaultdict |
| 2 | + |
| 3 | + |
| 4 | +def max_points(points): |
| 5 | + """slope: (y2-y1)/(x2-x1)""" |
| 6 | + def get_slope(point_a, point_b): |
| 7 | + try: |
| 8 | + return (point_b[1] - point_a[1]) / (point_b[0] - point_a[0]) |
| 9 | + except: |
| 10 | + return "undefined" |
| 11 | + |
| 12 | + def check_straight_line(points): |
| 13 | + slope = set() |
| 14 | + for i in range(len(points)-1): |
| 15 | + slope.add(get_slope(points[i], points[i+1])) |
| 16 | + return len(slope) == 1 |
| 17 | + |
| 18 | + num_of_coordinates = len(points) |
| 19 | + if num_of_coordinates < 3: |
| 20 | + return num_of_coordinates |
| 21 | + # below var to store slope and and co-ordinates that were used to get this slope |
| 22 | + slopes_and_points = defaultdict(list) |
| 23 | + for i in range(num_of_coordinates): |
| 24 | + for j in range(i+1, num_of_coordinates): |
| 25 | + slope = get_slope(points[i], points[j]) |
| 26 | + # print(slope) |
| 27 | + if points[i] not in slopes_and_points[slope]: |
| 28 | + slopes_and_points[slope].append(points[i]) |
| 29 | + if points[j] not in slopes_and_points[slope]: |
| 30 | + slopes_and_points[slope].append(points[j]) |
| 31 | + |
| 32 | + # now we have slope and points that are used to get the slope, we now need to check whether these points make straight line or not |
| 33 | + # below var to store total co-ordinates used for each slope in chronological order |
| 34 | + slope_and_its_total_points = [] |
| 35 | + for slope, coordinates in slopes_and_points.items(): |
| 36 | + if check_straight_line(coordinates): |
| 37 | + slope_and_its_total_points.append(len(coordinates)) |
| 38 | + return max(slope_and_its_total_points) |
| 39 | + # return slopes_and_points |
| 40 | + |
| 41 | + |
| 42 | +# test below |
| 43 | +# print(max_points([[1, 1], [2, 2], [3, 3]])) |
| 44 | +# print(max_points([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]])) |
| 45 | +# print(max_points([[0, 0]])) |
| 46 | +# print(max_points([[0, 0], [1, -1], [1, 1]])) |
| 47 | +# print(max_points([[3, 3], [1, 4], [1, 1], [2, 1], [2, 2]])) |
| 48 | +print(max_points([[0, 0], [4, 5], [7, 8], [8, 9], [5, 6], [3, 4], [1, 1]])) |
0 commit comments