0
classs = input("Class [1, 2 or 3] -  ")

if clas
        data = f.readlines()
        for le:
                print(line)
                found = True
        if found == False:
            print("False")

Here is a typical printed output:

John = 10
John = 6
John = 4

I need to be able to create an average just by using the 10, 4, 6 as I need to know a way to isolate the rest and allow the numbers to proceed inorder to create the average score.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
KryptoModz
  • 13
  • 6

3 Answers3

0

If the format of each line is the same, you can use string.split and cast to int:

classs = input("Class [1, 2 or 3] -  ")
l = []

if classs =='1':
    name = input("What is your name? -  ")

    datafile = '1.txt'
    found = False

    with open(datafile, 'r') as f:
        data = f.readlines()
        for line in data:
            if name in line:
                print(line)
                l.append(int(line.split()[2]))
                found = True
        if found == False:
            print("False")

Then go through the list of numbers and get the average, something like:

total = 0
num = 0
for x in l:
    total = total + x
    num = num + 1
print(total/num)
Ryan
  • 2,058
  • 1
  • 15
  • 29
  • Sorry for the nuisance, but using them 3 results how will I find the average? The format of the outputted results has confused me. – KryptoModz Oct 21 '15 at 22:33
  • Could you please? Give me any insight im really stuck! – KryptoModz Oct 21 '15 at 22:54
  • By calling your list `list`, you're taking over the [builtin function list()](https://docs.python.org/2/library/functions.html#list) and making your code more confusing. – TessellatingHeckler Oct 21 '15 at 23:49
  • One question, when the program outputs the average it outputs it after each results for example - John = 1 Your average is 1.0 John = 3 Your average is 2.0 my question is how do i get it to output the average after it outputs the last score. Instead of after each consecutive score? – KryptoModz Oct 23 '15 at 21:06
  • Where did you put the average calculator? Put it after the "with open" block. – Ryan Oct 26 '15 at 16:15
0

one way would be to extract the last 3 numbers for each player from your list (i'm assuming you only need 3, if not this code can be altered for more)

Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
    count = 0 
    record = line
    studentList = record.split(': ')
    score = studentList[1].strip('\n')
    studentList = [studentList[0], score]
    if len(dataList) == 0:
        dataList.append(studentList)
    else:
        while count < len(dataList):
            if studentList[0] == dataList[count][0]:
                if len(dataList[count]) == 4:
                    dataList[count][3] = dataList[count][2]
                    dataList[count][2] = dataList[count][1]
                    dataList[count][1] = score
                    break
                dataList[count].append(score)
                break
            elif count == len(dataList) - 1:
                dataList.append(studentList)
                break
            count = count + 1

this will give you a 2D array. each smaller array within will conatin the persons name at index 0 and there three numbers at indecies 1,2 and 3. now that you have these, you can simply work out the average.

AverageScore = []
# this is the array where the student' record (name and highest score) is saved
# in a list
count = 0
while count < len(dataList):
    entry = []
# this is whre each student name and score will be temporarily held
    entry.append(dataList[count][0])
# this makes it so the array 'entry' contains the name of every student
    Sum = 0
    frequency = len(dataList[count])
    incount = 1
    while incount < frequency:
        Sum = Sum + int(dataList[count][incount])
        incount = incount + 1 
    average = Sum / (frequency-1)
    entry.append(average)
    AverageScore.append(entry)
# this appends the name and average score of the student to the larger array
# 'AverageScore'
    count= count + 1
# the count is increased so the process is repeated for the next student
AverageSorted = sorted(AverageScore,key=lambda l:l[1], reverse=True)
# http://stackoverflow.com/questions/18563680/sorting-2d-list-python
# this is code i obtained through someone else's post which arranges the array in descending
# order of scores
count2 = 0
while count2 < len(AverageSorted):
    print(AverageSorted[count2][0], ':', AverageSorted[count2][1])
    count2 = count2 + 1
# this formats the array so it prints the elements in a list of each student's
# name and score

Long winded and inefficient, but its the best i can do with my small knowledge of python :)

callumbous
  • 173
  • 1
  • 1
  • 12
  • How do you extract the numbers within the list? Could you possibly put then into a variable which you can then easily make an average? – KryptoModz Oct 21 '15 at 22:57
0

If this is the content of 1.txt:

John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13

Replace your "with" statement with this:

name = "John"
_class = 1

with open("%s.txt" % _class, "r") as out:
    lines = out.readlines()

    scores = []

    for line in lines:
        if name in line:
            # "strip" without arguments strips out all beginning
            # and trailing white-space (i.e. " ", "\n", "\r").
            line = line.strip()

            score = int(line.split(" = ")[1])

            scores.append(score)

    # If there isn't any scores in this list, then there was no user
    # data.
    if scores:
        # Use python built-in sum to sum the list of scores and
        # divide the result by the number of scores gives you the average.
        average = sum(scores) / len(scores)

        print "%s's average score is %.1f out of %d game(s)." % (
            name, average, len(scores))

    else:
        print "User %s not found." % name
tlovely
  • 645
  • 1
  • 5
  • 15