程序对Python中一行的点数进行计数
假设我们有一个坐标列表。每个坐标都有两个值x和y,代表笛卡尔平面上的一个点。现在找到某条线上的最大点数。
因此,如果输入像座标=[[6,2],[8,3],[10,4],[1,1],[2,2],[6,6],[7,7]],则输出将为4,这是因为点位于线上的[1、1],[2、2],[6、6],[7、7]]。
例
让我们看下面的实现以更好地理解-
class Solution:
def solve(self, points):
res = 0
for i in range(len(points)):
x1, y1 = points[i][0], points[i][1]
slopes = {}
same = 1
for j in range(i + 1, len(points)):
x2, y2 = points[j][0], points[j][1]
if x2 == x1:
slopes[float("inf")] = slopes.get(float("inf"), 0) + 1
elif x1 == x2 and y1 == y2:
same += 1
else:
slope = (y2 - y1) / (x2 - x1)
slopes[slope] = slopes.get(slope, 0) + 1
if slopes:
res = max(res, same + max(slopes.values()))
return res
ob = Solution()
coordinates = [[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]
print(ob.solve(coordinates))输入值
[[6, 2],[8, 3],[10, 4],[1, 1],[2, 2],[6, 6],[7, 7]]输出结果
4