Select random scores from a .txt file and find their average (Python)… here is a solution to the problem.
Select random scores from a .txt file and find their average (Python)
I’ve been trying to randomly select scores from .txt files and then find out the average of these randomly selected scores. Here’s an example:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964
For simplicity, I just want to randomly pick 2 scores as a start. See below:
James, 0.974
Harry, 0.971 <---
Ben, 0.968
Tom, 0.965 <---
George, 0.964
The end result will be (Harry and Tom):
Average = 0.968
Can someone help? I’ve been using “split”, “random import”, etc. But I’m not very good at putting them together. It’s embarrassing, but here’s what I’ve gotten so far….
import random
stroke = random.choice(open('stroke.txt').readlines())
for x in stroke:
name, score = stroke.split(',')
score = int(score)
stroke.append((name, score))
print(stroke)
Solution
Try this (code explanation):
import random
# read the file in lines
with open('file.txt','r') as f:
lines = f.read().splitlines()
# split in ',' and get the scores as float numbers
scores = [ float(i.split(',')[1]) for i in lines]
# get two random numbers
rs = random.sample(scores, 2)
# compute the average
avg = sum(rs)/len(rs)
print avg
Now if you want to modify your code, you can do this:
import random
# pick two instead of one
stroke = random.sample(open('file.txt').readlines(),2)
scores = []
for x in stroke:
# split item of list not the list itself
name, score = x.split(',')
# store the two scores on the scores list
scores.append(float(score))
print (scores[0]+scores[1])/2
As @MadPhysicist suggested in the comment, instead of doing (scores[0]+scores[1]
)/2 a more general approach is sum(scores)/len(
fractions), as this applies even to more than two fractions.