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

Functions depending on other functions in Python

def mean(x):
    return(sum(x)/len(x))

def variance(x):
    x_mean = mean(x)
    return sum((x-x_mean)**2)/(len(x)-1)

def standard_deviation(x):
    return math.sqrt(variance(x))

The functions above build on each other. They depend on the previous function. What is a good way to implement this in Python? Should I use a class which has these functions? Are there other options?

>Solution :

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

Because they are widely applicable, keep them as they are

Many parts of a program may need to calculate these statistics, and it will save wordiness to not have to get them out of a class. Moreover, the functions actually don’t need any class-stored data: they would simply be static methods of a class. (Which in the old days, we would have simply called "functions"!)

If they needed to store internal information to work correctly, that is a good reason to put them into a class

The advantage in that case is that it is more obvious to the programmer what information is being shared. Moreover, you might want to create two or more instances that had different sets of shared data. That is not the case here.

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