Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
itertools.combinations() solution in Clear category for The Rows of Cakes by ddavidse
import itertools
""" For each 3 points, we use the first 2 points to find the a,b that satisfy
the line equation y = a*x + b for both points. Then, we check whether the
3rd point also lies on the line.
Because such lines cannot be vertical (this would require a == infinity),
we first have some additional logic to deal with constant x values. """
def checkio(cakes):
count = 0
x_stored = []
lines = []
for triplet in itertools.combinations(cakes, 3):
s1 = set([x[0] for x in triplet])
s2 = set([x[1] for x in triplet])
xval = s1.pop()
if not s1:
if xval not in x_stored:
count += 1
x_stored.append(xval)
elif len(s1) == 1 or len(s2) == 2:
continue
else:
x1 = triplet[0][0]
x2 = triplet[1][0]
x3 = triplet[2][0]
y1 = triplet[0][1]
y2 = triplet[1][1]
y3 = triplet[2][1]
a = (y1 - y2) / (x1 - x2)
b = y1 - x1 * a
if abs(a * x3 + b - y3) < 1e-5 and [a,b] not in lines:
lines.append([a,b])
count += 1
return count
Dec. 21, 2020