HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding average word length in a given year

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yearlengthaveragewordfindinggiven

Problem

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

Solution

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

Code Snippets

for word in words:
        for nary in words[word]:
for word, nary_list in words.items():
        for nary in nary_list:
if word_count != 0:
        return total_word_length / word_count
    return 0

Context

StackExchange Code Review Q#71114, answer score: 2

Revisions (0)

No revisions yet.