Reducing the length of the code


#1

The code below worked fine, but I was wondering if there are ways of shortening it. In its current version, it seems a little unwieldy.

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    return .1 * average(student["homework"]) + \
    .3 * average(student["quizzes"]) + \
    .6 * average(student["tests"])

#2

If something lacks purpose, remove it. Several lines in your code have no purpose. Go through them and ask yourself why and if each line is required.

I imagine several tools would even warn about them. For example:

$ pychecker ekrafleetfoot.py 
Processing module ekrafleetfoot (ekrafleetfoot.py)...

Warnings...

ekrafleetfoot.py:2: Local variable (homework) not used
ekrafleetfoot.py:2: No global (average) found
ekrafleetfoot.py:3: Local variable (quizzes) not used
ekrafleetfoot.py:4: Local variable (tests) not used

and another:

$ pyflakes ekrafleetfoot.py 
ekrafleetfoot.py:2: undefined name 'average'
ekrafleetfoot.py:2: local variable 'homework' is assigned to but never used
ekrafleetfoot.py:3: undefined name 'average'
ekrafleetfoot.py:3: local variable 'quizzes' is assigned to but never used
ekrafleetfoot.py:4: undefined name 'average'
ekrafleetfoot.py:4: local variable 'tests' is assigned to but never used
ekrafleetfoot.py:5: undefined name 'average'
ekrafleetfoot.py:6: undefined name 'average'
ekrafleetfoot.py:7: undefined name 'average'

.. while I'm dumping the results of running tools on your code, here's from a stylechecker:

$ pycodestyle ekrafleetfoot.py
ekrafleetfoot.py:6:5: E122 continuation line missing indentation or outdented
ekrafleetfoot.py:7:5: E122 continuation line missing indentation or outdented

#3

You are aware that this question has to do with Lesson 11, yes? If you were to run this single string through a checker, of course it would throw errors left and right.

Perhaps I should rephrase my question so it's easier to understand in the context of the lesson:

Is it possible to modify the above string in such a way that it is more concise AND fulfills the requirements for Lesson 11? I admit I don't know much about programming; that's why I'm learning.


#4

You should read again @ionatan's post. Take a look at this part:

ekrafleetfoot.py:2: Local variable (homework) not used
ekrafleetfoot.py:2: No global (average) found
ekrafleetfoot.py:3: Local variable (quizzes) not used
ekrafleetfoot.py:4: Local variable (tests) not used

The first line states that you have created a local variable called homework and you haven't used it, even once. This simply means that this line:

homework = average(student["homework"])

is redundant and you can delete it.


You will find in his post everything that you need to improve your code. Just read carefully and try to understand.


#5

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