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.
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
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.
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