我是python的新手,非常渴望学习这门语言。但是,现在我需要有人帮助我正在处理的代码,并继续标记此错误: 哎呀,再试一次。 get_average(alice)返回None而不是预期的91.15
以下是我的解决方案的问题: 编写一个名为get_average的函数,它将学生字典(如劳埃德,爱丽丝或泰勒)作为输入并返回他/她的加权平均值。
定义一个名为get_average的函数,它接受一个名为student的参数。 做一个可变的家庭作业,存储学生的平均值("作业"]。 重复步骤2进行"测验"和"测试"。 将3个平均值乘以它们的权重并返回这三个的总和。作业为10%,测验为30%,测试为60%。
我的解决方案:
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]
}
# Add your function below!
def average(numbers):
total = sum(numbers)
total = float(total)
result = total/len(numbers)
return result
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
print Av
答案 0 :(得分:1)
或者,你也可以试试这个:
import numpy as np
def weighted_average(d):
"""Returns weighted average of values corresponding to keys homework,
tests & quizzes of a dictionary d"""
# bind dict keys to variables homework, test, quiz
homework, test, quiz = [d["homework"]], [d["tests"]], [d["quizzes"]]
# calculate average through np.mean() and Return the value
return "Average: {}".format((0.1 * np.mean(homework)) + (0.6 * np.mean(test)) + (0.3 * np.mean(quiz)))
d = lloyd = {"name": "Lloyd","homework": [90.0, 97.0, 75.0, 92.0],"quizzes": [88.0, 40.0, 94.0],"tests": [75.0, 90.0]}
averages(d)
>>>'Average: 80.55'
答案 1 :(得分:0)
我已经测试了您的代码,修复了第4行(looyd测验)中缺少的左括号,并且它运行良好。
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]
}
# Add your function below!
def average(numbers):
total = sum(numbers)
total = float(total)
result = total/len(numbers)
return result
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
print Av
get_average(alice)
此代码在我的python 2.7上打印91.15