'python "TypeError: 'builtin_function_or_method' object is not iterable"
im trying to make a function that calculates the mad in a list but after i was done making it, it didnt work and said 'TypeError: 'builtin_function_or_method' object is not iterable' and i dont know why is said this. heres the code.
def mad(a):
mean = sum(a)/len(a)
absoluteDeviation = []
for eachValue in input:
absoluteDeviation.append(abs(eachValue - mean))
eachValue += 1
mad = sum(absoluteDeviation)/len(absoluteDeviation)
print(mad)
mad([2,4,6,8])
Solution 1:[1]
instead of
for eachValue in input:
It should be:
for eachValue in a:#since a is the iterable not input
there is no need for:
eachValue += 1
Code:
def mad(a):
mean = sum(a)/len(a)
absoluteDeviation = []
for eachValue in a:
absoluteDeviation.append(abs(eachValue - mean))
#eachValue += 1
return sum(absoluteDeviation)/len(absoluteDeviation)
print(mad([2,4,6,8]))
Output:
$python3.10 iterable.py
2.0
A better approach to calculate mean absolute deviation since we are using less memory as compare to above code:
"""
mean absolute deviation
"""
def mad(a):
mean = sum(a)/float(len(a))
mean_absolute_deviation = 0
for eachValue in a:
mean_absolute_deviation += abs(eachValue - mean)
mean_absolute_deviation /= len(a)
return mean_absolute_deviation
print(mad([2,4,6,8]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
