Functions depending on other functions in Python

Question:

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?

Asked By: program1232123

||

Answers:

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.

Answered By: Eureka
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.