Project Euler 102

http://projecteuler.net/index.php?section=problems&id=102


高2くらいで習うベクトルの計算をするだけです。

def read_triangles():
    file = open("triangles.txt")
    return [ tuple(map(float, s.split(','))) for s in file.readlines() ]
    file.close()

def contains_origin(triangle):
    x1, y1, x2, y2, x3, y3 = triangle
    a = (x2 - x1, y2 - y1)
    b = (x3 - x1, y3 - y1)
    r = (-x1, -y1)
    det = a[0] * b[1] - a[1] * b[0]
    s = (b[1] * r[0] - b[0] * r[1]) / det
    t = (-a[1] * r[0] + a[0] * r[1]) / det
    return 0 < s < 1 and 0 < t < 1 and s + t < 1

triangles = read_triangles()
print sum(map(contains_origin, triangles))