Search code examples
pythonyield

using yield print output


This is a continuation from here.

I am using yield statement instead of return.

This is the code:

class Measurements():
    def __init__(self, value, other):
        self.value = value
        self.other = other


class Criteria():
    def __init__(self, new_value, measurements):
        self.new_value = new_value
        self.measurements = measurements

    def method(self):
        for measurement in self.measurements:
            if 20 < measurement.value < 110:
                measurement.value = self.new_value
        return self.measurements

class Evaluate():
    def __init__(self, criteria):
        self.criteria = criteria

    def execute(self):
        for c in self.criteria:
            c.method()
            yield c.measurements


def main():
    criteria = [
        Criteria(999, [Measurements(100, 0.3), Measurements(33, 0.5)]),
        Criteria(999, [Measurements(150, 0.3), Measurements(35, 0.5)]),
    ]

    compare =  [
        Measurements(999, 0.3), Measurements(999, 0.5),
        Measurements(100, 0.3), Measurements(999, 0.5)
    ]

    obs = Evaluate(criteria).execute()

    # here compare

if __name__ == "__main__":
    main()

I want to compare my output values from obs with the values in the compare. I am refering to the Measurements part.

So, from obs, we have (for the variable value after running the code) :999,999,150,999 ( because if 20

and from compare we have: 999,999,100,999


Solution

  • Still a bit unsure on what checks you wanted to perform, but here is an example that should get you started. Couple of changes were made

    # Made compare a list contain lists of Measurements to match criteria
    compare =  [
        [Measurements(999, 0.3), Measurements(999, 0.5)],
        [Measurements(100, 0.3), Measurements(999, 0.5)]
    ]
    

    # Added __repr__ method to Measurement class
    def __repr__(self):
        return '{0} {1}'.format(self.value, self.other)
    

    I suggest doing this whenever you have a list of class instances, it makes debugging much easier as instead of getting this, you get something more meaningful.

    <__main__.Measurements object at 0x0000000003E2C438>
    

    Now for comparing the values I used zip to group the two lists together making it easier to compare the values. Then for the inner for loop we again zip the nested lists from each group together. From here each item is a Measurement that we can check their values of.

    for crit_lst, comp_lst in zip(obs, compare):
        for crit_meas, comp_meas in zip(crit_lst, comp_lst):
            print(crit_meas, comp_meas)
            if crit_meas.value != comp_meas.value: # example of comparing their values
                print('Mis-Match', crit_meas.value, comp_meas.value)