Generalise gridutil.coord methods

This commit is contained in:
akp 2024-12-01 11:33:50 +00:00
parent 770217e6bd
commit 507cd82fa4
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755

View file

@ -1,34 +1,36 @@
from enum import Enum, auto from enum import Enum, auto
from collections import namedtuple from collections import namedtuple
from numbers import Number from numbers import Number
from typing import TypeVar, Callable, Union
Coordinate = namedtuple("Coordinate", ["x", "y"]) Coordinate = namedtuple("Coordinate", ["x", "y"])
Coordinate3 = namedtuple("Coordinate3", ["x", "y", "z"]) Coordinate3 = namedtuple("Coordinate3", ["x", "y", "z"])
AnyCoordinate = Coordinate | Coordinate3
def add(a: Coordinate, b: Coordinate) -> Coordinate: def _coordmap(a: AnyCoordinate, b: AnyCoordinate, fn: Callable) -> AnyCoordinate:
xa, ya = a at = type(a)
xb, yb = b return at(*map(fn, zip(a, b)))
return Coordinate(xa + xb, ya + yb)
def sub(a: Coordinate, b: Coordinate) -> Coordinate: def add(a: AnyCoordinate, b: AnyCoordinate) -> AnyCoordinate:
xa, ya = a return _coordmap(a, b, lambda x: x[0] + x[1])
xb, yb = b
return Coordinate(xa - xb, ya - yb)
def mult(a: Coordinate, b: Number) -> Coordinate: def sub(a: AnyCoordinate, b: AnyCoordinate) -> AnyCoordinate:
x, y = a return _coordmap(a, b, lambda x: x[0] - x[1])
return Coordinate(x * b, y * b)
def manhattan_dist(a: Coordinate, b: Coordinate) -> Number: def mult(a: AnyCoordinate, b: Number) -> AnyCoordinate:
x, y = sub(b, a) at = type(a)
return abs(x) + abs(y) return at(*map(lambda x: x * b, a))
def manhattan_dist(a: AnyCoordinate, b: AnyCoordinate) -> Number:
return sum(map(abs, sub(b, a)))
def area(x: list[Coordinate]) -> Number: def area(x: list[Coordinate]) -> Number:
""" """
Finds the area of a closed polygon. Finds the area of a closed polygon.