使用字符串存储python数学测验的分数

时间:2015-03-30 21:06:39

标签: python file math

需要安排数学测验的分数:

- 按字母顺序排名,得分高 - 从最高分到最高分 - 从平均得分最高到最低 如果可能的话,我想用字符串来做这个,如果你能告诉我怎么做,我将不胜感激。我正在考虑使用字符串,但我不知道你是怎么做的。 我到目前为止的代码是:

import random
def start_quiz():
    print("Welcome to my Maths quiz")
#this creates a subroutine to enter the users name
def get_name():
    global name
    global group

    name=input("What is your name?")
    while name=="":
          name=input("What is your name?")
          group=input("What class are you in-1,2 or 3?")
    while group=="":
          group=input("What class are you in?")
    print("Hello " + name)

def questions():
    global score
    global questionnumber
    score=0
    questionnumber=0
    while questionnumber<10:
        questionnumber=questionnumber+1 
        operatorlist=['+','-','*']
        num1=random.randint(1,10)
        num2=random.randint(1,10)
        op=random.choice(operatorlist)
        if op=='-' and num2>num1:
            expression="%d %s %d" % (num2,op,num1)
        else:
            expression="%d %s %d" % (num1,op,num2)
        answer=eval(expression)
        enter_answer=1
        while enter_answer==1:
            try:
                useranswer= int(input(expression))
                enter_answer=0
            except ValueError:
                print("that was not a number, please re enter your answer")
        answer=int(answer)
        if useranswer==answer:
            print("well done")
            score=score+1
            print(" ")
        else:
            print("incorrect the correct answer is %d " % (answer))




def end_quiz():
    print("The quiz is now over")
    print("Well done " + name+". Your score is %d out of 10" % (score))

def savethescore():
    global score
    score=str(score)
    if group=='1':
        file=open("Scoreforclass1.txt",'a')
        file.write("\n")
        file.write ("Name: "+name+"\n")
        file.write('Class: '+group+'\n')
        file.write("Score: "+score+"/10\n")
        file.close()
    elif group=='2':
        file=open("Scoreforclass2.txt",'a')
        file.write("\n")
        file.write ("Name: "+name+"\n")
        file.write('Class: '+group+'\n')
        file.write("Score: "+score+"/10\n")
        file.close()
    else:
        file=open("Scoreforclass3.txt",'a')
        file.write("\n")
        file.write ("Name: "+name+"\n")
        file.write('Class: '+group+'\n')
        file.write("Score: "+score+"/10\n")
        file.close()


 def play_again():
     again= input("would you like to play again? y for yes and n for no")
     while again not in ['Y','y','N','n']:
         again = input("please enter 'Y' or 'N'")
     if again== 'y' or 'Y':
        do_the_quiz()
     else:
         print("cheers lad thanks for playing")
         exit()


def do_the_quiz():
    start_quiz()
    get_name()
    questions()
    end_quiz()
    savethescore()
    play_again()

do_the_quiz()   

如果可能的话,你可以尝试使用字符串,因为我尝试使用csv文件,但它太复杂了。提前谢谢。

1 个答案:

答案 0 :(得分:2)

这应该适合你。

import re
from functools import reduce

data=""
try:
    data+=open("Scoreforclass1.txt","r").read()
except:
    pass
try:
    data+=open("Scoreforclass2.txt","r").read()
except:
    pass
try:
    data+=open("Scoreforclass3.txt","r").read()
except:
    pass
allscores_name={}
allscores_score={}
averagescore_score={}

pattern=re.compile("Name: [^\n]*?\nClass: [^\n]*?\nScore: [^\n]*?\n")
data=pattern.findall(data)
for line in data:
    start=line.find("Name: ")+len("Name: ")
    end=line.find("\n",start)
    name=line[start:end].strip()
    start=line.find("Class: ",end)+len("Class: ")
    end=line.find("\n",start)
    classnum=line[start:end].strip()
    start=line.find("Score: ",end)+len("Score: ")
    end=line.find("/10\n",start)
    score=line[start:end].strip()
    if(name+classnum in allscores_name):
        allscores_name[name+classnum].append(int(score))
    else:
        allscores_name[name+classnum]=[int(score)]
    if(int(score) in allscores_score):
        allscores_score[int(score)].append(name+classnum)
    else:
        allscores_score[int(score)]=[name+classnum]

out=open("sortedbyname.txt",'w+')
for name in sorted(allscores_name.keys()):
    average=reduce(lambda x, y: x + y,map(int,allscores_name[name])) / float(len(allscores_name[name]))
    if(average in averagescore_score):
        averagescore_score[average].append(name)
    else:
        averagescore_score[average]=[name]
    for score in sorted(allscores_name[name]):
        out.write("\n")
        out.write ("Name: "+name[:-1]+"\n")
        out.write('Class: '+name[-1]+'\n')
        out.write("Score: "+str(score)+"/10\n")
out.close()

out=open("sortedbyscore.txt",'w+')
for score in sorted(allscores_score.keys())[::-1]:
    for name in sorted(allscores_score[score]):
        out.write("\n")
        out.write ("Name: "+name[:-1]+"\n")
        out.write('Class: '+name[-1]+'\n')
        out.write("Score: "+str(score)+"/10\n")
out.close()

out=open("sortedbyaverage.txt",'w+')
for avgscore in sorted(averagescore_score.keys())[::-1]:
    out.write("\n")
    out.write ("Name: "+name[:-1]+"\n")
    out.write('Class: '+name[-1]+'\n')
    for name in sorted(averagescore_score[avgscore]):
        for score in sorted(allscores_name[name])[::-1]:
            out.write("Score: "+str(score)+"/10\n")
out.close()

干杯!