yalqaoud / pwp-capstones

0 stars 0 forks source link

Removing some unnecessary code from get_average_sentence_length #1

Open jmcrey opened 5 years ago

jmcrey commented 5 years ago
def get_average_sentence_length(text):
    # creating a list of sentences called sentences_in_text:
    sentences = text.replace("?", ".").replace("!", ".").replace(",", "")
    sentences_in_text = sentences.split(". ")
    for sentence in sentences:
            sentence.split("? ")

    # creating a list of each sentence's words:
    words = []
    for sentence in sentences_in_text:
        words.append(sentence.split())

    # setence lengths (count by words):  
    sentence_lengths = [len(sentence) for sentence in words]

    # total lengths of sentences:
    sentences_count = len(words) #or len(sentence_lengths)

    sentence_lengths_total = 0
    for length in sentence_lengths:
        sentence_lengths_total += length

    average_sentence_length = sentence_lengths_total / sentences_count

    return average_sentence_length

So, this function returns the output we want -- great job with the correct implementation! I especially love the list comprehension in this line: sentence_lengths = [len(sentence) for sentence in words]. Really great job!

I just wanted to quickly point out that there are two places in the code that we could remove or replace. First, we can completely remove the following for loop:

    for sentence in sentences:
            sentence.split("? ")

Since we already perform the replace on the question mark, this for loop does not actually accomplish anything -- all of the question marks are gone from the string.

Second, we can replace the last for loop with the sum function. Specifically, we can replace

    sentence_lengths_total = 0
    for length in sentence_lengths:
        sentence_lengths_total += length

with

average_sentence_length = sum(sentence_lengths) / sentences_count

The sum function simply returns the sum (or total) of a list of integers. So, we can completely remove the for loop and replace it with the built-in sum function to simplify the code a little bit.

Otherwise, this function does a great job at returning the correct average sentence length -- I just wanted to point out some places we could simplify. Nice job!

yalqaoud commented 5 years ago

@jmcrey Thanks for the feedback, it is greatly appreciated!