Skip to content

Commit 507cd82

Browse files
committed
Generalise gridutil.coord methods
1 parent 770217e commit 507cd82

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

gridutil/coord.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,36 @@
11
from enum import Enum, auto
22
from collections import namedtuple
33
from numbers import Number
4+
from typing import TypeVar, Callable, Union
45

56

67
Coordinate = namedtuple("Coordinate", ["x", "y"])
78
Coordinate3 = namedtuple("Coordinate3", ["x", "y", "z"])
9+
AnyCoordinate = Coordinate | Coordinate3
810

911

10-
def add(a: Coordinate, b: Coordinate) -> Coordinate:
11-
xa, ya = a
12-
xb, yb = b
13-
return Coordinate(xa + xb, ya + yb)
12+
def _coordmap(a: AnyCoordinate, b: AnyCoordinate, fn: Callable) -> AnyCoordinate:
13+
at = type(a)
14+
return at(*map(fn, zip(a, b)))
1415

1516

16-
def sub(a: Coordinate, b: Coordinate) -> Coordinate:
17-
xa, ya = a
18-
xb, yb = b
19-
return Coordinate(xa - xb, ya - yb)
17+
def add(a: AnyCoordinate, b: AnyCoordinate) -> AnyCoordinate:
18+
return _coordmap(a, b, lambda x: x[0] + x[1])
2019

2120

22-
def mult(a: Coordinate, b: Number) -> Coordinate:
23-
x, y = a
24-
return Coordinate(x * b, y * b)
21+
def sub(a: AnyCoordinate, b: AnyCoordinate) -> AnyCoordinate:
22+
return _coordmap(a, b, lambda x: x[0] - x[1])
2523

2624

27-
def manhattan_dist(a: Coordinate, b: Coordinate) -> Number:
28-
x, y = sub(b, a)
29-
return abs(x) + abs(y)
25+
def mult(a: AnyCoordinate, b: Number) -> AnyCoordinate:
26+
at = type(a)
27+
return at(*map(lambda x: x * b, a))
3028

3129

30+
def manhattan_dist(a: AnyCoordinate, b: AnyCoordinate) -> Number:
31+
return sum(map(abs, sub(b, a)))
32+
33+
3234
def area(x: list[Coordinate]) -> Number:
3335
"""
3436
Finds the area of a closed polygon.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy