-1

I am trying to sort a data file by student name so that I get all of the student names with their classcode and score on the same line. I manage to sort in name order but the data is not split on to separate lines nor does it put the associated classcode or score with each name.

The code is:

import random
q=0
ans=0
studentnames = []
ascending = []


classcode = input("Enter your class (1,2 or 3): ")

if classcode == '1':
name=input("Enter your name: ")
n= int(input("Enter the number of questions you want to attempt: "))

#writing details to a txt file group1

text_file1 = open("data.dat", "a")


while q<n:                  
    c = random.randint(1,3)
    print("c is: ", c)

    if c==1:   
        f="+"

        num1 = random.randint(0,12)
        print("num1 is: ", num1)

        num2 = random.randint(0,10)
        print("num2 is: ", num2)

        product=num1*num2
        difference=num1-num2
        total=num1+num2

        d=total

        q+=1

        print("\n Question ", q)
        print ("What is  ",num1,f,num2," ? ")

        l=int(input("Enter Your Answer: "))
        if l==d:
            print ("\nCongratulations! your answer is right.\n")
            ans+=1
        else:
            print("\n I'm afraid your answer is wrong. The correct one is" ,d)            

    elif c==2:         
        f="*"

        num1 = random.randint(0,12)
        print("num1 is: ", num1)

        num2 = random.randint(0,10)
        print("num2 is: ", num2)

        product=num1*num2
        difference=num1-num2
        total=num1+num2

        d=product


        q+=1

        print("\n Question ", q)
        print ("What is  ",num1,f,num2," ? ")

        l=int(input("Enter Your Answer: "))
        if l==d:
            print ("\nCongratulations! your answer is right.\n")
            ans+=1
        else:
            print("\n I'm afraid your answer is wrong. The correct one is" ,d)

    else:         
        f="-"

        num1 = random.randint(0,12)
        print("num1 is: ", num1)

        num2 = random.randint(0,10)
        print("num2 is: ", num2)

        product=num1*num2
        difference=num1-num2
        total=num1+num2

        d=difference

        q+=1 # counter for questions

        print("\n Question ", q)
        print ("What is  ",num1,f,num2," ? ")

        l=int(input("Enter Your Answer: "))
        if l==d:
            print ("\nCongratulations! your answer is right.\n")
            ans+=1 # counter for answers
        else:
            print("\n I'm afraid your answer is wrong. The correct one is" ,d)

# calculating the percentage
x=float(ans)
y=float(q)
z=ans*100/q
cp=int(z)
print("Your Correct percentage = ",cp,"%\n")

#store details in a list
scores=[classcode,name,cp]
print(scores)

#writing to text file
text_file1.write(classcode )
text_file1.write(' ')
text_file1.write(name )
text_file1.write(' ')

#converting score to string so that it can be written to txt file
scr = str(cp)
text_file1.write(scr )

#adding a new line after each students score
text_file1.write("\n")

#close the txt file after it has been used
text_file1.close()

#reading the txt file
text_file1 = open("data.dat", "r")
print(text_file1.read())
text_file1.close()


f = open("data.dat", "r")
for line in f:
 fields = line.split()
 classcode = fields[0]
 name = fields[1]
 scr = str(fields[2])
 studentnames.append(classcode)
 studentnames.append(name)
 studentnames.append(scr)
 print(classcode, name, scr)



f = open("data.dat", "r")
for line in f:
fields = line.split()
classcode = fields[0]
name = fields[1]
scr = str(fields[2])
studentnames.sort()
ascending.append(studentnames)
print(ascending)

The data file that I am trying to sort in name order is:

1 test2 100

1 test1 100

1 test3 20

1 test4 60

1 test5 33

1 aguero 100

1 aguero 100

1 aguero 100

1 aguero 50

1 test3 60

1 1 100

1 test3 50

1 test2 100

1 test1 100

1 test4 50

1 messi 100

1 messi 100

1 ronaldo 100

1 ronaldo 100

1 maradonna 100

1 maradonna 100

1 maradonna 100

Thanks

Tim
  • 41,901
  • 18
  • 127
  • 145

1 Answers1

0

This codes reads the data file, sorts the records by name and displays the results.

import operator

with open("data.dat") as f:
  students = []
  for line in f:
    fields = line.split()
    students.append( (fields[0], fields[1], int(fields[2])) )

# sort by the student's name
sortedByName = sorted(students, key=operator.itemgetter(1))

for r in sortedByName:
  classcode, name, score = r
  print "name:", name, "classcode:", classcode, "score:", score
ErikR
  • 51,541
  • 9
  • 73
  • 124
  • I suppose if I want to sort on a second field like score then I would do something like this after the sortedbyname: Sortedbyscore = sorted(score, key=operator.itemgetter(2)) – Darth Sidius Nov 30 '14 at 15:44
  • I have tried to add the following to sort on a secondary field but doesnt seem to work: sorted(sortedByName, key =operator.itemgetter(2), reverse=True) # sorting on second item – Darth Sidius Nov 30 '14 at 16:28
  • That's right. And to sort first on score and then by name you can use `operator.itemgetter(2,1)` – ErikR Nov 30 '14 at 16:29
  • I tried the operator.itemgetter(1,2) to sort on name and then score but that didn't work which is why I tried the above to try sorting on the second field in a different way but no luck... – Darth Sidius Nov 30 '14 at 16:32
  • The problem is that the `score` field is a string, not a number. I've updated the answer to convert the score field using `int()` – ErikR Nov 30 '14 at 16:37
  • tried that but get an error: Traceback (most recent call last): data file test.py", line 145, in students.append( (fields[0], fields[1], int(fields[2])) ) ValueError: invalid literal for int() with base 10: 'persie' – Darth Sidius Nov 30 '14 at 16:49
  • In your data file you have the string 'persie' in the column you are trying to convert to an integer - so either your data file is bad or you have the wrong column. – ErikR Nov 30 '14 at 17:16
  • corrected the data file, Don't get any errors, but the sort on the score field does not work. I have used key=operator.itemgetter(1,2) – Darth Sidius Nov 30 '14 at 17:36
  • Post your code and data to pastebin.com and tell me what the urls are. – ErikR Nov 30 '14 at 17:40
  • http://pastebin.com/5kY7cNvj – Darth Sidius Nov 30 '14 at 17:46
  • http://pastebin.com/vgKz5PyK – Darth Sidius Nov 30 '14 at 17:47
  • first one is code second one is data – Darth Sidius Nov 30 '14 at 17:48
  • Why do you have lines 133-135? And line 152 is commented out, so you are not doing anything with the sorted data. After uncommenting out line 152 If I run your program and input '2', I see the scores sorted first by name and then by score. – ErikR Nov 30 '14 at 18:38
  • I have been trying out allsorts of different options so the code is a bit of a mess, I have been working on different files so I didn't realise the commented out line 152. Cheers for this works as it should. Can I set a parameter for True=reverse to get the scores in reverse order? – Darth Sidius Nov 30 '14 at 18:43
  • See [this SO question](http://stackoverflow.com/questions/1516249/python-list-sorting-with-multiple-attributes-and-mixed-order) for sorting multiple fields and mixing the sort orders on each field. – ErikR Nov 30 '14 at 18:58
  • I have done this but it doesn't sort within the name group, it sorts by score: import operator with open("data.dat") as f: students = [] for line in f: fields = line.split() students.append( (fields[0], fields[1], int(fields[2])) ) # sort by the student's name sortedByName = sorted(students, key=operator.itemgetter(1)) sortedByName = sorted(sortedByName, key=operator.itemgetter(2), reverse=True) for r in sortedByName: classcode, name, score = r print("name:", name, "classcode:", classcode, "score:", score) – Darth Sidius Nov 30 '14 at 19:46
  • You should start a new SO question. – ErikR Nov 30 '14 at 19:51