Reputation: 31
I've been trying to select scores at random from a .txt file and then finding the average of these randomly selected scores. Below is an example:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964
For the sake of simplicity, I'd just like to select 2 scores at random to start with. See below:
James, 0.974
Harry, 0.971 <---
Ben, 0.968
Tom, 0.965 <---
George, 0.964
The end result would then be (Harry and Tom):
Average = 0.968
Can anyone help? I've been using 'split', 'import random' etc. But I'm not great at putting these all together. This is embarrassing, but here's what I've got 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)
Upvotes: 3
Views: 147
Reputation: 12972
Try with this (explanation on the code):
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 wanted to modify your code you could do it like 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 proposed in the comments, instead of doing (scores[0]+scores[1])/2
a more general way would be sum(scores)/len(scores)
since this would work even for more than just two scores.
Upvotes: 3
Reputation: 91
Passing as string, but you can change it from file
import random
scoresString = '''
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964
'''
# How much randoms
randomCount = 2
# Get lines of the pure string
linesPure = scoresString.split("\n")
# Get lines that have content
rowsContent = [line for line in linesPure if(line.strip())]
# Get random lines
chosenRows = random.sample(rowsContent, randomCount)
# Sum of chosen
sum = 0
for crow in chosenRows:
sum += float(crow.split(",")[1].strip())
# Calculate average
average = sum / len(chosenRows)
print("Average: %0.3f" % average)
Upvotes: 0
Reputation: 488
Assuming that the scores.txt
file is formatted like so:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964
Then this should do the trick:
import random
scores = open('scores.txt','r').read()
scores = scores.split('\n')
for i in range(len(scores)):
scores[i] = scores[i].split(', ')
scores[i][1] = float(scores[i][1]) * 1000
def rand_avg_scores(scorelist):
score1 = scorelist.pop(random.randint(0,len(scorelist)-1))
score2 = scorelist.pop(random.randint(0,len(scorelist)-1))
finalscore = (score1[1] + score2[1])/2000
return score1[0], score2[0], finalscore
print(rand_avg_scores(scores))
I added the * 1000
and /2000
bit to account for floating point errors. If the scores have more significant digits, add more zeroes accordingly.
Upvotes: 0