4
\$\begingroup\$

I have written a function which takes the year in question and words as a data which is a dictionary that maps words to the list of year/count. Now I am wondering how I can improve the code that I have or how to make it more simpler or make it better performance-wise.

def avgWordLen(year, words):
    totLen = 0
    totword = 0
    for word in words:
        for nary in words[word]:
            if nary.year == year:
                totLen += len(word) * nary.count
                totword += nary.count
    if totword != 0:
        return totLen / totword
    else:
        return 0
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

totword and totLen are not so good names. And in any case PEP8 suggests to use snake_case for both variable and function names. So I recommend the following renames:

  • total_word_length instead of totLen
  • word_count instead of totword
  • average_word_length instead of avgWordLen

When you iterate over keys in a dictionary and then lookup the values in every iteration step, then it's better to iterate over the dictionary items. That is, instead of:

    for word in words:
        for nary in words[word]:

Do like this:

    for word, nary_list in words.items():
        for nary in nary_list:

This way you avoid unnecessary dictionary lookups.

At the end of the method, the else is unnecessary, because the if part always returns. It's slightly simpler this way:

    if word_count != 0:
        return total_word_length / word_count
    return 0
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.