-2

After finding the range, min, max and average from my text file of stored scores of my game, I would like to find the standard deviation from these scores but I am not sure how to go about it.

This is what I have so far:

file = open('stats.txt', 'a+')
file.write('\n' + 'Score: ' + str(1))
file.close()

numbers = []
with open('stats.txt') as fh:
    count = 0
    for line in fh:
        count += 1
        numbers.append(float(line.split()[1]))

file = open('maths.txt', 'w+')
file.write('Average Score: ' + str(sum(numbers)/len(numbers)) + "\n")
file.write('Maximum Score: ' + str(max(numbers)) + "\n")
file.write('Minimum Score: ' + str(min(numbers)) + "\n")
maxn = max(numbers)
minn = min(numbers)
rangex = (maxn) - (minn)
file.write('Range of Scores: ' + str(rangex))
file.close()

What my text file looks like:

Score: 3
Score: 0
Score: 13
Score: 13
Score: 9
Score: 0
Score: 0
Score: 0
Score: 0
Score: 0
Score: 0
Score: 31
Score: 0
Score: 0
Score: 0
Score: 0
Score: -8
Score: 0
Score: 0

Thanks for helping

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58

2 Answers2

0

You just need to use the standard deviation function from numpy.

Add to the beginning of your code:

import numpy as np

and then use:

file.write('Standard Deviation: ' + str(np.std(numbers)) + "\n")
Guilherme Costa
  • 308
  • 2
  • 13
0

You can read the file and split on : to create a list:

l = []

In [400]: with open('stats.txt', 'r') as f:
     ...:     for i in f:
     ...:         l.append(int(i.split(':')[1].strip()))


In [401]: l
Out[401]: [3, 0, 13, 13, 9, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, -8, 0, 0]

In [403]: import statistics
In [402]: statistics.stdev(l)
Out[402]: 8.357158922932953

OR you can use numpy also:

In [404]: import numpy as np
In [403]: np.std(l)
Out[403]: 8.1342611825629
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58