0
lloyd = {
    "name": "Lloyd",
    "homework": [90, 97, 75, 92],
    "quizzes": [88, 40, 94],
    "tests": [75, 90]
}
alice = {
    "name": "Alice",
    "homework": [100, 92, 98, 100],
    "quizzes": [82, 83, 91],
    "tests": [89, 97]
}
tyler = {
    "name": "Tyler",
    "homework": [0, 87, 75, 22],
    "quizzes": [0, 75, 78],
    "tests": [100, 100]
}

def get_average(student):
    weight = 0
    total = 0
    for item in student:
        if item == "homework":
            weight = .1
        elif item == "quizzes":
            weight = .3
        elif item == "tests":
            weight = .6
        else:
            weight = 0
        total += student[item] * weight

    return total

get_average(tyler)

ここで何が起こっているのですか?それは私にそれを言ってエラーを与えています

student[item]整数以外で乗算できませんでした - 浮動小数点数

4

2 に答える 2

1

文字列とリストに浮動小数点数を掛けようとしていますが、これは不可能です。

student[item] * weight

このようなことを試してください:

def get_average(student):
    weight = 0
    total = 0
    for item,val in student.items(): #use dict.items() if you need to wrk on both key and values
        if item == "homework":
            weight = .1
        elif item == "quizzes":
            weight = .3
        elif item == "tests":
            weight = .6
        else:
            continue    # no need of weight = 0 simple move on to next item
                        # continue statement jumps the loop to next iteration
        total += (float(sum(val)) / len(val)) * weight
    return total

print get_average(tyler)  #prints 79.9
于 2013-05-12T03:46:40.390 に答える