How to use Class to iterate over an array?

Question:

I’m working on Python classes, but I’m running into a "not iterable" error; however, at least from what I can tell, it should iterable.

class Stuff:
    def __init__(self, values):
        self.values = values
    
    def vari(self):
        mean = sum(self.values)/len(self.values)
        _var = sum((v - mean)**2 for v in self.values) / len(self.values)
        return _var

    def std_dev(self):
        print(sqrt(vari(self.values)))

Basically, I have a class called stuff that takes in "values," which in this case will be

x = [12, 20, 56, 34, 3, 17, 23, 43, 54]

from there, values are fed into a function for variance and then a function for std_dev, but I’m still getting the nor iterable error. I know I can use numpy and stats for std_dev and variance, but I’m trying to work on classes. Any help would be appreciated.

Asked By: Tyrone_Slothrop

||

Answers:

Is this what you wanted !?

Code:-

import math
class Stuff:
    def __init__(self,values):
        self.values = values
    
    def vari(self):
        mean = sum(self.values)/len(self.values)
        _var = sum((v - mean)**2 for v in self.values) / len(self.values)
        return _var

    def std_dev(self):
        return math.sqrt(self.vari())
x=[12, 20, 56, 34, 3, 17, 23, 43, 54]
a=Stuff(x)
print(a.vari())
print(a.std_dev())

Output:-

311.2098765432099
17.64114158843497
Answered By: Yash Mehta
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.