Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python, create a kind of template for functions

I have a class with three functions that do almost the same things but on different objects. And I think there is a better way to program it since it is a duplication of code, but I cannot see how to have a kind of template. Here is my example:

    def averageEndEffectorVelocity(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeVelocity) < samplingSize:
            return -1
        else:
            return sum(self.eeVelocity[-samplingSize:])/samplingSize

    def averageEndEffectorAcceleration(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeAcceleration) < samplingSize:
            return -1
        else:
            return sum(self.eeAcceleration[-samplingSize:])/samplingSize

    def averageEndEffectorJerk(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeJerk) < samplingSize:
            return -1
        else:
            return sum(self.eeJerk[-samplingSize:])/samplingSize

One can see that each function is calculating the average of the last samplingSize values of the velocity, acceleration and jerk. Is there a way to have a better code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Make this function work fully on parameters passed to it (can be made class or static method, or refactored outside of the class completely):

def averageEndEffector(data, samplingSize=cst.AVERAGE_SIZE):
    if len(data) < samplingSize:
        return -1
    else:
        return sum(data[-samplingSize:])/samplingSize

Now all your instance methods can simply take the form of:

    def averageEndEffectorVelocity(self, samplingSize=cst.AVERAGE_SIZE):
        return averageEndEffector(data=self.eeVelocity, samplingSize=cst.AVERAGE_SIZE)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading