Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用字符串存储python数学测验的分数_Python_File_Math - Fatal编程技术网

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

使用字符串存储python数学测验的分数,python,file,math,Python,File,Math,数学测验的分数需要安排: -按姓名字母顺序排列,高分 -由最高分到最低分 -由平均分最高到最低 如果可能的话,我想用字符串来做这件事,如果你能告诉我怎么做,我将不胜感激。我正在考虑使用字符串,但我不知道你会怎么做。 到目前为止,我掌握的代码是: import random def start_quiz(): print("Welcome to my Maths quiz") #this creates a subroutine to enter the users name def ge

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

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

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()   
随机导入
def start_测验():
打印(“欢迎参加我的数学测验”)
#这将创建一个子例程来输入用户名
def get_name():
全局名称
全球集团
name=输入(“你叫什么名字?”)
而name==“”:
name=输入(“你叫什么名字?”)
组=输入(“你在哪一个班-1、2或3?”)
而组==“”:
组=输入(“你在哪个班?”)
打印(“你好”+姓名)
定义问题():
全球得分
全局问题编号
分数=0
问题编号=0
而问题编号NUM1:
expression=“%d%s%d”%(num2,op,num1)
其他:
expression=“%d%s%d”%(num1,op,num2)
答案=评估(表达式)
输入答案=1
当输入_answer==1时:
尝试:
useranswer=int(输入(表达式))
输入答案=0
除值错误外:
打印(“那不是一个数字,请重新输入您的答案”)
答案=int(答案)
如果useranswer==答案:
打印(“做得好”)
分数=分数+1
打印(“”)
其他:
打印(“不正确正确答案为%d”%(答案))
def end_quick():
打印(“测验现在结束”)
打印(“做得好”+姓名+”。你的分数是10分中的%d分(分数))
def savethescore():
全球得分
分数=str(分数)
如果组=='1':
文件=打开(“Scoreforclass1.txt”,“a”)
文件。写入(“\n”)
file.write(“名称:“+Name+”\n”)
file.write('Class:'+group+'\n')
file.write(“分数:“+Score+”/10\n”)
file.close()文件
elif组=='2':
文件=打开(“Scoreforclass2.txt”,“a”)
文件。写入(“\n”)
file.write(“名称:“+Name+”\n”)
file.write('Class:'+group+'\n')
file.write(“分数:“+Score+”/10\n”)
file.close()文件
其他:
文件=打开(“Scoreforclass3.txt”,“a”)
文件。写入(“\n”)
file.write(“名称:“+Name+”\n”)
file.write('Class:'+group+'\n')
file.write(“分数:“+Score+”/10\n”)
file.close()文件
再次播放()
再次=输入(“您想再次播放吗?y表示是,n表示否”)
而不是在['Y','Y','N','N']中:
再次=输入(“请输入‘Y’或‘N’”)
如果再次=='y'或'y':
做测验
其他:
打印(“干杯,小伙子,谢谢玩”)
退出()
def完成测验():
开始测验()
获取名称()
问题()
完(小测验)
savethescore()
再玩一次
做测验

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

这应该适合你

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()

干杯

那么你的问题是什么呢?尝试使用文本文件来完成问题开头的三件事“如果你可以创建代码来完成这件事”不是一个有效的问题。请说明你是如何试图解决这个问题的,即使只是用文字描述你认为应该如何解决。你需要遵循哪些步骤才能完成你想做的事情?您需要使用一些字符串,是的,但是您还需要数字来计算排名和平均值。你的数据来自哪里?一旦计算出来,它会去哪里?考虑所有这些,然后将其转换为Python。如果您有关于该代码的特定问题,请随时提问。AttributeError:“dict”对象没有属性“iterkeys”。如果您使用的是Python 3,则可以将iterkeys()更改为keys()。iterkeys()在Python 3中失去了支持。我已经编辑了我的答案。它不起作用,它不会在3个新创建的文本文件中写名字和分数。它说reduce没有定义?它现在可以与Python 3.4一起使用。reduce()已移动到functools.reduce(),如顶部第二次导入所示。如果对你有效,请接受答案。