2015-01-06 3 views
-4

저는 개인 프로젝트에서 작업 해 왔으며, 개발이 완전히 중단 된 문제를 발견했습니다. 코드 조각은 다음을 수행 할 수 있어야합니다.알파벳순 및 숫자순 텍스트 문서 정렬 없음

  • 무작위로 생성되고 더하기, 빼기 및 곱하기를 사용하는 10 가지 기본 질문 세트를 사용자에게 인쇄하십시오. 응답을 받아 들여야하며 사용자에게 대답이 올바른지 알려줍니다. 그러면 점수가 업데이트됩니다.
  • 코드에는 이름과 점수와 함께 각 사람 점수가 저장됩니다.
  • 저장된 정보는 사전 순, 숫자 순, 평균 순으로 정렬 할 수 있어야합니다.

상위 2 개의 작업을 완료 할 수있었습니다. (내 코드에서 볼 수 있듯이 실행 해보십시오!)

정렬에 도움이 필요합니다. 여기

ValueError: invalid literal for int() with base 10: ''

(정렬 기능이없는) 모든 코드입니다 : 여기에 나를 던져 된 오류는

def quiz() : 
    for i in range(0,1): 
     import random 
     from operator import add, sub, mul; 

     # Asks for a name. 
     name = input("What is your name? ") 
     # Asks for the group number. 
     group = input("Which class are you in? 1, 2 or 3? ") 

     operations = (add, sub, mul) 
     operator = random.choice(operations) 

     # Sets the users score to zero. 
     score = 0 

     # Sets the indented part of code to repeat 10 times. 10 Questions will be printed. 
     for i in range(0,10): 

      calculations = ('+', '-', '*') 
      operator = random.choice(calculations) 

      if operator == "+": 
       calculation = add 
      if operator == "-": 
       calculation = sub 
      if operator == "*": 
       calculation = mul 

      # This function adds the first and second number into the sum. It also determines what numbers will be displayed, between 1 and 10.  
      a, b, d, c = (random.randint(1,10), operator, random.randint(1,10),calculation) 

     #Prints the question 
      print(a, b, d) 

     #Creates an input for the answer 
      acd = int(input("Your answer: ")) 

      e = calculation(a, d) 

     #Marks the question, and udates the users score depending on result of answer. Correct or Incorrect. 
      if acd == e: 
       print('Correct') 
       score = score+1 

      elif acd: 
       print('Incorrect') 
       score = score+0 
# Gives the user brief feedback abou their score. 
     if score == 10: 
      print('Well done, you are great at maths ' +str(name)) 
     if score <6: 
      print('You should try harder next time!' +str(name)) 
     if score <3: 
      print('You should take extra maths lessons!' +str(name)) 

     print("Your score is: " +str(score)) 
# Outputs the data to a text document, sorted by class. 
     if group == "1": 
      with open("class1results.txt", "a") as myfile: 
       myfile.write("\nName: " +str(name) +"\n Score: " +str(score)) 
       myfile.close() 
       print('Your test data has been recorded.') 
# Outputs the data to a text document, for group 2.    
     if group == "2": 
      with open("class2results.txt", "a") as myfile: 
       myfile.write("\nName: " +str(name) +"\n Score: " +str(score)) 
       myfile.close() 
       print('Your test data has been recorded.') 
# Outputs the data to a text document, for group 3. 
     if group == "3": 
      with open("class3results.txt", "a") as myfile: 
       myfile.write("\nName: " +str(name) +"\n Score: " +str(score)) 
       myfile.close() 
       print('Your test data has been recorded.')   

     alphabetSort() 

# Asks the user to take the quiz again. 
     question = input("Would you like to run the quiz for another student?") 
     if question == "Yes": 
       quiz() 
     if question == "yes": 
       quiz() 
     if question == "No": 
      exit() 
     if question == "no": 
      exit() 



# Runs the quiz again, to start the looping off. 
quiz() 

나는 그것이 복잡 알고 있지만, 그것을 작동합니다! (! 그냥 약 : /)

+2

정렬 코드 또는이 오류의 원인이되는 코드를 게시하십시오. 귀하의 질문에서 말하기 어렵습니다. – JeffThompson

+2

데이터에 빈 문자열이 있습니다. 빈 문자열은 정수로 변환 될 수 없습니다. –

+0

* 아래에 게시 한 스크립트로 [...] 정렬했습니다. 스크립트를 게시하는 것을 잊었습니다. –

답변

0

는 무엇보다도 당신은 아마 JSON 또는 다른 쉽게 분석 할 수있는 형식으로 점수를 저장해야

하지만

import re 
def get_scores(fname): 
    scores = {} 
    for name,score in re.findall("Name: (.*)\n Score: (.*)",open(fname).read()): 
     if name in scores: 
      scores[name].append(score) 
     else: 
      scores[name] = [score] 
    return scores 

이 당신에게 매핑 이름의 사전을 줄 것이다 점수의 목록

{"bob":[1,2,3],"Sam":[5,6,7],...} 

지금 당신은 당신의 정렬 함수를 작성

def sort_by_name(data): 
    return sorted(data) 
def sort_by_max_score(data): 
    return sorted(data,key=lambda x:max(data[x])) 
def sort_by_average(data): 
    return sorted(data,key=lambda x:float(sum(data[x]))/len(data[x]) 

그러면 구문 분석기가 만든 사전으로 정렬 함수를 호출하십시오.