Here is my solution to the previous problem.
class Environment:
def __init__(self, times, values):
self.__times = times
self.__values = values
def __integrate_trapezoid(self, v):
x = self.__times[v]
y = self.__values[v]
return sum(0.5*(x[i] - x[i-1])*(y[i] + y[i-1]) for i in range(1, len(x)))
def get_times(self, v):
return self.__times[v]
def get_values(self, v):
return self.__values[v]
def compute_v1(self):
return self.__integrate_trapezoid('A') - self.__integrate_trapezoid('B')
def compute_v2(self):
all_v = ( self.get_values('A') + self.get_values('B') +
self.get_values('C') + self.get_values('D') )
return sum(all_v) / len(all_v)
def compute_v3(self):
a_b = self.__integrate_trapezoid('A') - self.__integrate_trapezoid('B')
c_d = self.__integrate_trapezoid('C') + self.__integrate_trapezoid('D')
return a_b / c_d
def compute_v4(self):
return sorted(self.get_times('A') + self.get_times('B') +
self.get_times('C') + self.get_times('D'))
And then I modified the read_instrument_data
function to return an Environment
instance.
def read_instrument_data(filename):
values = {}
times = {}
with open(filename) as f:
for record in f:
var,time,value = record.split(',')
if var not in values:
values[var] = []
times[var] = []
values[var].append(float(value))
times[var].append(float(time))
return Environment(times, values)
Now, we should be able to test this new class out to see if it gives the same results as we got previously.
env = read_instrument_data('instrument2.csv')
env.get_times('A')
env.get_values('A')
env.compute_v1()
env.compute_v2()
env.compute_v3()
env.compute_v4()
Looks correct!
Sometimes the data itself doesn't have to be complicated; it can just be numerous! And when the data describing different aspects of the same thing grows like that, the complexity can show up in both the number of variables used to describe the different aspects of the same thing grows, the signatures of the functions operating on that data can grow and get complex, too! You can reduce a lot of burden on the user (and yourself) if you bundle all of that data and those functions together into a object.