Calculating arithmetic mean (one type of average) in Python
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
Simple arithmetic average in Python
n = input('Number of terms')
acc = 0
for i in range(1,int(n)+1):
a=input('Term number '+str(int(i))+': ')
acc += float(a)
print('The average is ',acc/int(n))
The idea is to create an accumulator variable acc
to which the entered numbers are added. After the loop acc
is equal to the sum of all numbers entered. Divide it by the number of terms and you get the arithmetic average.
Finding the average of a list
For Python 3.8+, use statistics.fmean
for numerical stability with floats. (Fast.)
For Python 3.4+, use statistics.mean
for numerical stability with floats. (Slower.)
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
For older versions of Python 3, use
sum(xs) / len(xs)
For Python 2, convert len
to a float to get float division:
sum(xs) / float(len(xs))
Arithmetic mean for 'i' elements
The simplest and most efficient way is to keep separately the sum and the count of element of the input list. Then the arithmetic mean if just the current sum divided by the current count:
def mari(x):
s = 0.0 # current sum
cnt = 0 # current count
m = [] # list to return
for i in x:
s += i
cnt += 1
m.append(s / cnt)
return m
Calculating arithmetic mean from a list
Your code is quite verbose but correct nonetheless. Below, you can find a more pythonic solution:
import random
numberList = []
for _ in range(1000):
numberList.append(random.randrange(1, 7))
# or simply using a list comprehension
# numberList = [random.randrange(1, 7) for _ in range(1000)]
print(sum(numberList)/len(numberList)) # I got 3.587, 3.556, 3.529 which is close to what you would expect (3.5)
Note that the solution proposed above saves memory as well as it does not define as many variables (x
, count
, list_sum
)
How to calculate mean in python?
Convert you list from strings to np.float:
>>> gp = np.array(goodPix, np.float)
>>> np.mean(gp)
96.906260000000003
Calculating the average of specific numbers in a mixed text file?
You need to represent the data, currently you are returning tuples from reading the file.
Store them in a list, create methods to filter your students on theire major and one that creates the avgGPA of a given student-list.
You might want to make the GPA a float on reading:
with open("s.txt","w") as f:
f.write("OLIVER\n8117411\nEnglish\n2.09\nOLIVIA\n6478288\nLaw\n3.11\n" + \
"HARRY\n5520946\nEnglish\n1.88\nAMELIA\n2440501\nFrench\n2.93\n")
def readStudents6(file):
name = file.readline().rstrip()
studentID = file.readline().rstrip()
major = file.readline().rstrip()
gpa = float(file.readline().rstrip()) # make float
return name, studentID, major, gpa
Two new helper methods that work on the returned student-data-tuples:
def filterOnMajor(major,studs):
"""Filters the given list of students (studs) by its 3rd tuple-value. Students
data is given as (name,ID,major,gpa) tuples inside the list."""
return [s for s in studs if s[2] == major] # filter on certain major
def avgGpa(studs):
"""Returns the average GPA of all provided students. Students data
is given as (name,ID,major,gpa) tuples inside the list."""
return sum( s[3] for s in studs ) / len(studs) # calculate avgGpa
Main prog:
students = []
with open("s.txt","r") as f:
while True:
try:
stud = readStudents6(f)
if stud[0] == "":
break
students.append( stud )
except:
break
print(students , "\n")
engl = filterOnMajor("English",students)
print(engl, "Agv: ", avgGpa(engl))
Output:
# all students (reformatted)
[('OLIVER', '8117411', 'English', 2.09),
('OLIVIA', '6478288', 'Law', 3.11),
('HARRY', '5520946', 'English', 1.88),
('AMELIA', '2440501', 'French', 2.93)]
# english major with avgGPA (reformatted)
[('OLIVER', '8117411', 'English', 2.09),
('HARRY', '5520946', 'English', 1.88)] Agv: 1.9849999999999999
See: PyTut: List comprehensions and Built in functions (float
, sum
)
def prettyPrint(studs):
for name,id,major,gpa in studs:
print(f"Student {name} [{id}] with major {major} reached {gpa}")
prettyPrint(engl)
Output:
Student OLIVER [8117411] with major English reached 2.09
Student HARRY [5520946] with major English reached 1.88
Related Topics
How to Get the Row Count of a Pandas Dataframe
I Expect 'True' But Get 'None'
Python 3.5 - "Geckodriver Executable Needs to Be in Path"
How to Make My Player Rotate Towards Mouse Position
Wrapping a C Library in Python: C, Cython or Ctypes
What's the Best Practice Using a Settings File in Python
Pyplot Common Axes Labels for Subplots
Numpy.Unique with Order Preserved
How to Transpose Dataframe in Pandas Without Index
Query for List of Attribute Instead of Tuples in SQLalchemy
How to Flatten Lists Without Splitting Strings
Reactornotrestartable Error in While Loop with Scrapy
How to Set a Default Parameter Equal to Another Parameter Value
Change the Colors Within Certain Range to Another Color Using Opencv
Naming Conflict with Built-In Function
Bin Elements Per Row - Vectorized 2D Bincount for Numpy