Display only words that have an even number of vowels within a sentence

Asked

Viewed 733 times

1

I need to make this code in which you scroll through a list and print to the user the words that have an even number of vowels. Follow the code:

frase = ["Foi magnifica a festa ontem."]

palavras = 0
vPalavras = 0
vogais = "aeiouAEIOU"

# separar palavra por palavra
for i in range(len(frase)):
  palavras = frase[i].split()

# descobrir quais palavras possuem vogais em par
for i in range(len(palavras)):
  for char in palavras[i]:
    if char in vogais:
        vPalavras += 1
    if vPalavras % 2 == 0:
      print(palavras[i])

So he does return something to me, but it’s only the first two words, ignoring "party" and "yesterday".

3 answers

2

Your code is, by very little, almost working.

The first problem, and the main one, is that you do not restart the vowel count with each word. As you did, the count will accumulate; so, instead of considering word for word, you end up always considering from the beginning of string.

To solve this, just add one vPalavras = 0 every time you change your word.

frase = ["Foi magnifica a festa ontem."]

palavras = 0
vPalavras = 0
vogais = "aeiouAEIOU"

# separar palavra por palavra
for i in range(len(frase)):
  palavras = frase[i].split()

# descobrir quais palavras possuem vogais em par
for i in range(len(palavras)):
  vPalavras = 0  # Reinicia o contador a cada palavra
  for char in palavras[i]:
    if char in vogais:
        vPalavras += 1
    if vPalavras % 2 == 0:
      print(palavras[i])

In this way, the output becomes:

Foi
Foi
magnifica
magnifica
magnifica
magnifica
festa
festa
ontem.
ontem.
ontem.

We have all the words we want, but repeated. Why? Well, notice that the word repeats exactly the same number of vowels that it has. Foi has two vowels, appearing twice; magnifica has four vowels, repeating four times. This is because you made the condition if vPalavras % 2 == 0 within the loop that traverses the characters of the word. Thus, for each character, whenever the total of vowels is even, the word will be displayed. We don’t want that, so just remove a level of indentation from this condition, leaving it within the loop that runs through the words:

frase = ["Foi magnifica a festa ontem."]

palavras = 0
vPalavras = 0
vogais = "aeiouAEIOU"

# separar palavra por palavra
for i in range(len(frase)):
  palavras = frase[i].split()

# descobrir quais palavras possuem vogais em par
for i in range(len(palavras)):
  vPalavras = 0  # Reinicia o contador a cada palavra
  for char in palavras[i]:
    if char in vogais:
        vPalavras += 1
  if vPalavras % 2 == 0:  # Aqui removi um nível de indentação
    print(palavras[i])

And with that, the result will be:

Foi
magnifica
festa
ontem.

Eureca! We have the desired result.


But why not other improvements in your code?

You start by defining the phrase:

frase = ["Foi magnifica a festa ontem."]

However, given the presence of the brackets, you will be creating a list of strings. If you need more phrases, it might be interesting to do this, but since you only have one, you just have to define how string only:

frase = "Foi magnifica a festa ontem."

To go through all the phrases, you did:

for i in range(len(frase)):
    palavras = frase[i].split()

Hardly in Python you will need to do range(len(...)) to go through something. That’s not readable - and if it’s not readable, it’s not pythonic. You might as well replace it with:

for frase in frases:
    palavras = frase.split()

But since we no longer have a list of strings, just you do:

palavras = frase.split()

To go through the words, too, is not necessary range(len(palavras)); one for palavra in palavras suffice.

for palavra in palavras:
    quantidade = 0
    for vogal in 'aeiouAEIOU':
        quantidade += palavra.count(vogal)

Note that instead of going through each character of the word and checking if it is a vowel, I went through each vowel and counted how many times it appears in the word, adding to the total. You can even simplify this code using comprehensilist on:

for palavra in palavras:
    quantidade = sum(palavra.count(vogal) for vogal in 'aeiouAEIOU')

This disregarding accentuated vowels, such as á, ã, é, etc.

So your code could be just:

frase = "Foi magnifica a festa ontem."
palavras = frase.split()
for palavra in palavras:
    quantidade = sum(palavra.count(vogal) for vogal in 'aeiouAEIOU')
    if quantidade % 2 == 0:
        print(palavra)
  • wow, just start the variable... thank you so much for all the tips! ;)

0

Your mistake is simple.

 if vPalavras % 2 == 0:

that code means, if the word remnant 2 equals zero so it prints, magnifica has 4 vowels, so 4%2 = 0, so it prints. I suggest using different nomenclature.

 if vPalavras / 2 == 1:

so you ensure that word division is ALWAYS 2 and not an even number

  • I was wrong to ask the question. I would like to return all the words in which the vowel numbers are even, that is: "Foi", "magnifica", "festa" and "yesterday", but only returns the first two.

0

Hello! Welcome to Python.

Initially your code creates a list with a string only inside, I suggest creating only the string, because the list is confusing here:

frase = "Foi magnifica a festa ontem."  # removido [] para não criar uma lista

Another suggestion for your whole life in python is to avoid using for i in range(len(palavras)): -- the for python already iterates in direct elements, so you will rarely need the index, most of the time you want to use is for palavra in palavras: and iterate directly on the words and not on the index.

EDITING: According to the comment below, it seems that "pairs of vowels" means "even number of vowels", so just count how many vowels there are in the word.

palavras = frase.split()
for palavra in palavras:
    if numero_de_vogais(palavra) % 2 == 0:
        print(palavra)

def numero_de_vogais(texto):
    return len([letra for letra in texto if letra in vogais])

There’s another way using the sum:

def numero_de_vogais(texto):
    return sum(1 for letra in texto if letra in vogais)
  • Thank you so much for the tips! It wasn’t quite that when I said "total pairs of vowels" it would be to print out all the words that vowels are pairs. In the example, for example, it should be "Foi", "magnifica", "festa" and "yesterday". But only the first two appear

  • @H.Lamarr edited the answer, see if you agree now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.