为什么这会返回错误的值?

时间:2015-10-11 09:22:26

标签: python

输入get_class_average(["Alice","Lloyd"])后,答案应为85.85,而是返回91.15

lloyd = {  
    "name": "Lloyd",  
    "homework": [90.0, 97.0, 75.0, 92.0],  
    "quizzes": [88.0, 40.0, 94.0],  
    "tests": [75.0, 90.0]  
}  
alice = {    
    "name": "Alice",   
    "homework": [100.0, 92.0, 98.0, 100.0],    
    "quizzes": [82.0, 83.0, 91.0],    
    "tests": [89.0, 97.0]  
}   
tyler = {   
    "name": "Tyler",    
    "homework": [0.0, 87.0, 75.0, 22.0],   
    "quizzes": [0.0, 75.0, 78.0],  
    "tests": [100.0, 100.0]   
}   

def average(numbers):   
    total = sum(numbers)   
    total = float(total)    
    tot = total / len(numbers)    
    return tot    
def get_average(student):    
    homework = average(student["homework"])    
    quizzes = average(student["quizzes"])    
    tests = average(student["tests"])  
    homework = homework * 0.1   
    quizzes = quizzes * 0.3   
    tests = tests * 0.6  
    return tests+quizzes+homework    
def get_letter_grade(score):   
    if score >= 90:  
        return "A"  
    elif score >= 80:  
        return "B"  
    elif score >= 70:  
        return "C"  
    elif score >= 60:  
        return "D"  
    else:  
        return "F"  

print get_letter_grade(get_average(lloyd))  

def get_class_average(students):  
    results = []  
    for x in students:  
        savg = get_average(x)  
        results.append(savg)  
        return average(results)  

3 个答案:

答案 0 :(得分:0)

get_average需要传递dict而不是学生的姓名。所以我很惊讶这种情况一直在发生:

请注意您调用get_class_average(["Alice","Lloyd"]) - 传递字符串列表。每个元素都未经修改地传递给get_average()

可能你应该说get_class_average([alice, lloyd])

答案 1 :(得分:0)

我的代码为我返回85.85 - 当使用正确的缩进时,get_class_average()传递一个字典列表而不是字符串列表。

get_class_average(["Alice","Lloyd"])实际上应该导致异常,因为您将学生作为字符串传递,而不是字典。将您的代码更改为:

print get_class_average([alice, lloyd])

并且您应该看到85.85已打印 - 一旦您在return中修复了最终get_class_average()语句的缩进,就像这样:

def get_class_average(students):  
    results = []  
    for x in students:  
        savg = get_average(x)  
        results.append(savg)  
    return average(results)  

您的代码在for循环体内缩进了return语句。因此,在函数返回之前,只计算一个平均值(对于alice),因此结果为91.15

我建议您修复这一行以取消return语句,然后将代码重新提交给代码学院。

答案 2 :(得分:0)

有效。

def get_class_average(学生):     results = []     对于学生:         results.append(get_average(student))     返回平均值(结果)