Created
September 8, 2022 15:44
-
-
Save mdales/1c84f449d49000406aab3296342a3a9f to your computer and use it in GitHub Desktop.
Now with arrays
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
#!/usr/bin/env python3 | |
class Foo: | |
def __init__(self, lhs, op=None, rhs=None): | |
self.lhs = lhs | |
if op: self.op = op | |
if rhs: | |
if len(lhs) != len(rhs): | |
raise ValueError("Mismatched array sizes") | |
self.rhs = rhs | |
def __str__(self): | |
try: | |
return f"({self.lhs} {self.op} {self.rhs})" | |
except AttributeError: | |
return str(self.lhs) | |
def __add__(self, other): | |
return Foo(self, "__add__", other) | |
def __sub__(self, other): | |
return Foo(self, "__sub__", other) | |
def __mul__(self, other): | |
return Foo(self, "__mul__", other) | |
def __truediv__(self, other): | |
return Foo(self, "__truediv__", other) | |
def __len__(self): | |
return len(self.lhs) | |
def eval(self, index=None): | |
try: | |
if index is not None: | |
return getattr(self.lhs.eval(index), self.op)(self.rhs.eval(index)) | |
else: | |
return [ | |
getattr(self.lhs.eval(idx), self.op)(self.rhs.eval(idx)) | |
for idx in range(len(self))] | |
except AttributeError: | |
try: | |
return self.lhs[index] | |
except TypeError: | |
return self.lhs | |
a = Foo([42.0, 34.0]) | |
b = Foo([7.0, 2.0]) | |
c = (a + b) / b | |
print(c) | |
print(c.eval()) | |
c = a + (b / b) | |
print(c) | |
print(c.eval()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version works with arrays, and should never hold intermediary values in the expression as arrays in memory
Output: