Last active
April 26, 2024 10:18
-
-
Save MawKKe/1fafc1f4a5eb79ed654cf0567c284651 to your computer and use it in GitHub Desktop.
Are you tired of plain old integer-based indexing? Use floats instead!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Are you tired of plain old integer-based indexing? | |
Use floats instead! | |
""" | |
# Author: Markus H (MawKKe) 2024-04 https://github.com/MawKKe | |
import math | |
import typing as t | |
import pytest | |
def lerp(a, b, scale: float) -> float: | |
assert 0 <= scale <= 1 | |
return (b-a) * scale + a | |
class InterpList(list): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.interp = kwargs.pop('interp', lerp) | |
def __getitem__(self, i: t.Union[float, int]): | |
a = super().__getitem__(math.floor(i)) | |
b = super().__getitem__(math.ceil(i)) | |
scale = i - math.floor(i) | |
return self.interp(a, b, scale) | |
def test_interplist(): | |
l = InterpList([2, 7, -1, 8]) | |
# old school integer indexing. ugh, so boring... | |
assert l[0] == 2 | |
assert l[1] == 7 | |
assert l[2] == -1 | |
assert l[3] == 8 | |
# index with floats, as mother nature intended | |
assert l[0.5] == pytest.approx(4.5, 0.001) | |
assert l[1.98] == pytest.approx(-0.8399, 0.001) | |
assert l[2.458] == pytest.approx(3.12, 0.001) | |
def test_interplist_fract(): | |
from fractions import Fraction as F | |
l = InterpList([F(2,7), F(1,8), -F(2,81)]) | |
assert l[F(1,2)] == F(23, 112) | |
assert l[1 + F(98,100)] == F(-703, 32400) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment