To solve this question we can use the following logic:
- Capture any sentence and add it to a list;
- Scroll through this list and capture the size of each word;
- Insert the size of each word in another list;
- Scroll through the two lists simultaneously associating each large word or its name.
With this logic I implemented the following code:
frase = input('Digite a frase: ').split()
tam_palavras = list()
for palavra in frase:
tam_palavras.append(len(palavra))
maior = max(tam_palavras)
print('Maior(es) palavra(s):')
for a, b in zip(frase, tam_palavras):
if b == maior:
print(a)
See here the operation of the programme.
Note that when we execute the code we receive the following message: Digite a frase:
. Right now we should type in any sentence and press enter
.
After we have inserted that sentence the code will execute the first time. It is through him that the list will be assembled tam_palavras
, in which the size of all words that may be in frase
. The tamanho
of the largest word and stored in the variable maior
.
Later the code executes the second for with the help of the function zip
. It is through it that both lists - phrase and tam_words - will be simultaneously traversed. Moreover the block if
which lies within the 2º for
, will verify if the size "b"
of each word is equal to greater. If yes, the word "a"
, listed frase
will be displayed on the screen.
Observing
The use of second for is highly necessary. Because, if there is more than one larger word in the sentence, they will all be displayed.
Example 1
If the phrase typed is
Eu acho que vi um gatinho
The Exit will be...
Maior(es) palavra(s):
gatinho
In this case we have a phrase with only one larger word size, which is gatinho
, and has 7 letters.
Example 2
If the phrase typed is:
Eu acho que vi um gatinho e uma gatinha
The exit will be...
Maior(es) palavra(s):
gatinho
gatinha
In this case we have a phrase with two larger words, which are; gatinho
and gatinha
. In this case each of the two words have 7 letters.
Yeah, I forgot about
len
. In case I use the functionmin()
it returns me the smallest element oftext
?– user141036
@Alexfeliciano If you use the same logic, yes.
– Woss
Got it, thanks for your help.
– user141036