Search code examples
pythonoopstatisticsmean

Python: Get mean and std dev from input using OOP


I have solved the following program to get mean and std dev from user's input, but I have the strong feeling that can be improved, mainly as I have to duplicate the split function, I had to do that because std_dev was using the mean result, so for that reason an error message was telling me that std_dev required at least two points.Here's my code, hope someone could help me out on this:The code uses "a" and "a_2" to avoid the problem above described:

import math
import statistics as st

class Data:
    def __init__(self, a, b)
        self.a = a
        self.b = b
        self.mean = st.mean(a)
        self.std_dev = st.stdev(a_2)

data_input = input("Enter data set:")
a = (float(x) for x in data_input.split(",")
a_2 = (float(x) for x in data_input.split(",")

data_1 = Data(a, 1.0)

print("Data mean is: %0.4f" %data_1.mean)
print("Standard Dev is: %0.4f" %data_1-std_dev)



Solution

  • The reason for the error message is that you are using a generator expression with round parentheses to create an iterable of float's and assigning it to a. So, a is a generator and is exhausted (empty) after you pass it to st.mean(). What you want is probably a list comprehension with square brackets, you will have a list that can be iterated as many times as you want.

    import statistics as st
    
    
    class Data:
        def __init__(self, data):
            self.data = data
            self.mean = st.mean(data)
            self.std_dev = st.stdev(data)
    
    
    data_str = input("Enter data set: ")
    data_set = [float(x) for x in data_str.split(",")]  # note the square brackets
    data = Data(data_set)
    print(f"Data mean is: {data.mean:.2f}")
    print(f"Standard Dev is: {data.std_dev:.2f}")
    

    You can read more about their differences in another SO post.