How to return the first vowel of several words in a list?

Asked

Viewed 167 times

3

The code is partially done, but it returns only the vowels found in each word.

How could I return only the first vowel of each word?

palavras = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma',)
vogais = ('a', 'e', 'i', 'o', 'u')

for palavras in palavras:
print(f'\nPalavra {palavras}', end=' ')
for letra in palavras:
    if letra in vogais:
        print(letra, end=' ')

Upshot:

Palavra boi o i 

Palavra vaca a a 

Palavra macaco a a o 

Palavra ovelha o e a 

Palavra lesma e a 

Process finished with exit code 0

  • Rephrasing the question.... The intention is to learn how to manipulate the elements of the string letter. For example, how could you return the last vowel of words?

  • If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

4 answers

5

insert a break after the print of the volgal:

palavras = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma',)
vogais = ('a', 'e', 'i', 'o', 'u')

for palavras in palavras:
    print(f'\nPalavra {palavras}', end=' ')
    for letra in palavras:
        if letra in vogais:
            print(letra, end=' ')
            break

and will have solved the problem!

  • Thanks a lot Juliano! With this question, I was trying to learn how to manipulate the elements of the string letters. For example, I would know how to bring the last vowel of each letter?

  • Voce can invert the word and continue returning the first vowel in case: words = ('ox', 'cow', 'monkey', 'sheep', 'slug',) vowels = ('a', 'e', 'i', 'o', 'u') for words in words: print(f' nPalavra {words}', end=' ') for letter in words[::-1]: if letter in vowels: print(letter, end=' ') break

  • If you want to use the other vowel positions I advise you to create a list with the vowels of each word, thus being able to access the position of caca one of them when necessary: words = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma',) vowels = ('a', 'e', 'i', 'o', 'u') for words in words: nvogais=[] print(f' nPalavra {words}', end=' ') for letter in words: letter if in vowels: nvogais.append(letter) print(oganvis[x], end=' ') where x is the desired vowel position

  • Thank you again Juliano! I managed to understand a little more about the manipulations of these elements

4

import re

palavras = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma',)

for palavra in palavras:
    try:
        print('Palavra ' , palavra , re.findall(r'a|e|i|o|u', palavra)[0])
    except:
        print('Palavra ' , palavra , ' não contém vogal')

With the library’re' you can pick up patterns in the stirng, and it will return you the Matches. For example, the word monkey will return to you: ['a', 'a', 'o']

To access the first element, simply access the index [0]. If you want the last element, as you answered in the question above, go to [-1], that will return you the last element of the list.

Add a Try Except in case there are no vowels in a word, then an empty list is returned, and when trying to access an index will pop an error.

  • Thanks a lot Matheus! Great reference for strings, I will study a little more this library.

4

Another interesting way to resolve this issue is by using the following code:

palavras = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma')

for palavra in palavras:
    for letra in palavra:
        if letra in 'aeiou':
            print(f'Para "{palavra}" a primeira vogal é: "{letra}"')
            break

Note that in this code I did not use a list containing the vowels. In this case I used a string sequence containing the 5 vowels located in the block line "if".

For the code to display only the first vowel is required that the second block for is interrupted immediately after the if block has found the first vowel of the respective word, and for this we need to use the break.

  • 1

    Thank you very much Solkarped!

4

An alternative is to apply a filter to your strings allowing them to pass only the vowels and collect the information.

The idea of the algorithm is to check every word of its tuple and do a search case insensitive by vowels, which is nothing more than a typographical search indifferent to the box or the algorithm is indifferent to upper and lower case. For example, for the algorithm "cow" and "COW" are the same word and the system identifies the two occurrences of the same vowel "to" what does not happen in an algorithm case sensitive for example for a box-sensitive algorithm whose search parameter is aeiou would be returned that word "COW" has no vowels.

To search for unstick vowels the method is used str.lower() which converts all alphabetic characters from a string to lowercase letters.

The search itself is done through a filtering where every word analyzed and subjected to the built in function filter(function, iterable) that nothing else does but apply a function function to one of the elements everlasting iterable and if the return of this function is True the rated element approved by the filter otherwise is rejected.

In this solution the function passed to filter is a lambda expression that nothing else is the definition of an anonymous function created through the keyword lambda. instead of something like:

def funcao_filtro(letra):
     return letra in vogais

filter(funcao_filtro , p)

I preferred to do something more lean:

filter(lambda l: l in vogais, p)

After that comes the simplest part of the algorithm which is to join the filtering result with str.join() and perform the analysis on the result.

Solution:

palavras = ('boi', 'vaca', 'macaco', 'ovelha', 'lesma', "kkk")
vogais = 'aeiou'

#Para cada palavra na tupla de palavras...
for palavra in palavras:
    #Converte as letras da palavra para minúscula para fazer a filtragem case-insensitive e evitar excessões.
    p = palavra.lower()   
    #Obtem o resultado da filtragem da palavra deixando apenas as vogais.
    r = "".join(filter(lambda l: l in vogais, p))
    #Compara o tamanho do resultado...
    if len(r) == 0:
        #...se igual a 0.
        msg = f'A palavra "{p}" não não possui vogais.'
    else:
        #... se maior que 0.
        msg = f'A palavra é "{p}":\n'
        msg += f'{" "*2}• a palavra possui {len(r)} vogais "{r}"\n' 
        msg += f'{" "*2}• a primeira vogal é "{r[0]}"\n'
        msg += f'{" "*2}• a última vogal é "{r[-1]}"'
    #Imprime a mensagem informando o resultado.
    print(msg)

Resulting:

A palavra é "boi":
  • a palavra possui 2 vogais "oi"
  • a primeira vogal é "o"
  • a última vogal é "i".
A palavra é "vaca":
  • a palavra possui 2 vogais "aa"
  • a primeira vogal é "a"
  • a última vogal é "a".
A palavra é "macaco":
  • a palavra possui 3 vogais "aao"
  • a primeira vogal é "a"
  • a última vogal é "o".
A palavra é "ovelha":
  • a palavra possui 3 vogais "oea"
  • a primeira vogal é "o"
  • a última vogal é "a".
A palavra é "lesma":
  • a palavra possui 2 vogais "ea"
  • a primeira vogal é "e"
  • a última vogal é "a".
A palavra é "kkk" e não possui vogais.
  • 1

    Very cool this solution, I did not know the LAMBDA function, I will study more about it. Thank you Augusto!

Browser other questions tagged

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