# Help with my code

#1

My code:
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]
}

students= [tyler, lloyd, alice]
for student in students:
def average(student):
total= float(sum(student))
total= total/float(len(student))
def get_average(student):
homework=average(student[“homework”])
quizzes=average(student[“quizzes”])
tests=average(student[“tests”])
weighted_total= homework*.1 + quizzes*.3 + tests*.6
return weighted_total
student.update({“weighted_total”: weighted_total})
return student
print average(tyler[“homework”])
print get_average(alice)
print lloyd

The output:
46.0
91.15
{‘quizzes’: [88.0, 40.0, 94.0], ‘tests’: [75.0, 90.0], ‘name’: ‘Lloyd’, ‘homework’: [90.0, 97.0, 75.0, 92.0]}

The details:
I completed the objective for the lesson, but I’m trying to get the program to created a new item in each dictionary and then store the weighted average in that new item.

#2

First we need to deal with the greatest concern… We cannot define a function in a loop (or shouldn’t, at least). Let those functions reside in the global namespace.

``````def average(student):
total = float(sum(student))
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return homework * 0.1 + quizzes * 0.3 + tests * 0.6
``````
``````for student in students:
student['wavg'] = get_average(student)
``````

#3

Thank you, it worked, but may you tell me why it worked.

#4

Why it works is kind of nebulous. How it works is a question that can be answered. Mechanics is how it works.

First we made the code functional by moving the definitions to global scope. The loop just got much simpler. One step simple.

We have a data structure that points to three object references.

``````students = [alice, lloyd, tyler]
``````

We iterate that list by object reference.

``````for student in students:
``````

Now we have an object reference upon which we can call the two helper functions.

``````student['wavg']
``````

creates a new key in the current dictionary (our object reference), and,

``````... = get_average(student)
``````

assigns the return value to that key. Job done.

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.