230k views
4 votes
Write a loop that reads in a collection of words and builds a sentence out of all the words by appending each new word to the string being formed. For example, if the three words This, is, one are entered, your sentence would be "this", then "This is", and finally "This is one". Exit your loop when a word that ends with a period is entered or the sentence being formed is longer than 20 words or contains more than 100 letters. Do not append a word if it was previously entered

1 Answer

2 votes

Answer:

#section 1

import re

wordcount = 0

lettercount = 0

words = ['This', 'is', 'one','one', 'great','Dream.', 'common', 'hella', 'grade','grace','honesty','diligence','format','young',]

sentence = []

#section 2

for a in words:

wordcount = wordcount + 1

for i in a:

lettercount= lettercount + 1

if a not in sentence:

sentence.append(a)

if lettercount > 100:

break

if wordcount > 20:

break

if re.search('(\w+\.$)', a):

break

sentence = ' '.join(sentence)

print(sentence)

Step-by-step explanation:

The programming language used is python.

#section 1

The regular expression module is imported because we need to use it to determine if a word entered ends with a full-stop.

Two variables are initialized to hold the number of words and the number of letters and an empty list is created to hold the sentence that is going to be created.

A collection of words are placed in a list in order test the code.

#section 2

Two FOR loops and a group of IF statements are used to check if the words entered satisfy any of the conditions.

The first FOR loop counts the number of words and the second one counts the number of letters.

The first IF statement checks to make sure the word has not been added to the sentence list and adds it if not present, while the next two IF statements check the word count and letter count to ensure that they have not exceeded 20 or 100 respectively and if they exceed, the loop is broken. The last IF statement uses regular expression to check if a word ends with a full-stop and if it does, it breaks the the loop.

Finally, the sentence list is joined and the sentence is printed to the screen.

Write a loop that reads in a collection of words and builds a sentence out of all-example-1
User Alexander Bortnik
by
7.6k points