I often find myself doing inefficient loops as such:
def __add__(self, other):
dimensions = []
for i in range(max(self.numberOfDimensions, other.numberOfDimensions)):
a = None
if i < self.numberOfDimensions:
a = self[i]
b = None
if i < other.numberOfDimensions:
b = other[i]
# Doesn't actually do the right thing here.
dimensions.append(sum(map(lambda x: ((x is None) and 1 or 2) - 1, (a, b))))
return self.__class__(dimensions)
The calculation is simple, it’s just handling the if statements types that’s getting me. By the way, this is a subclass of tuple in which the add operator adds similar index’s values like so (1, 2, 3) + (4, 5, 6, 7) == (5, 7, 9, 7). I would think that filter() would help me out on this but I’m not sure how I’d implement it.
EDIT: This is for Python 3.
The most concise way to do this is
or
This does what I guess your original code is supposed to do. If you are using Python 3, convert the result to a tuple or list or whatever you want it to be.