Home > Blockchain >  Given a list of different words, implement a function that returns the list of all words that contai
Given a list of different words, implement a function that returns the list of all words that contai

Time:12-30

I have written the code, but I am not getting the final result when I run the code, there seems to be some error in logic. Please help me as I am new to python.

My code

num = int(input("how many words do you want to enter in your list : \n"))

words = []

for i in range(num):
    a = input(f"enter your word no. {i 1} :  \n")
    words.append(a)

def words_with_all_vowels():
    vowels = ["a", "e", "i", "o", "u"]
    result = []
    count = 0
    for i in words:
        for j in i:
            for m in vowels:
                if j == m:
                    count  = 1
                    vowels.remove(m)
                    break
                else:
                    continue

        if count == 5:
            result.append(i)
        
        vowels = ["a", "e", "i", "o", "u"]
    return result

print(words_with_all_vowels())

I ran the code above and the terminal gave the following results:

how many words do you want to enter in your list : 
2
enter your word no. 1 :  
rahul
enter your word no. 2 :  
aeiou
[]                     # this is the final result and it's empty.

CodePudding user response:

Correct version of your function:

def words_with_all_vowels():
    vowels = ["a", "e", "i", "o", "u"]
    result = []
    for word in words:
        word_low = word.lower()
        count = 0
        for vowel in vowels:
            if vowel in word_low:
                count =1
            else:
                break
        if count == 5:
            result.append(word)
    return result

So here are the changes I made:
To begin with, the .lower() function lowered the word so that, for example, your example "aeiou" but with the capital letter "aEiou" would still display this word in the result.
Next, the counter must be reset for each word.
You can also check if there is any letter (or even a substring) in a string with the following line:\

if letter in word:

You don't have to remove a vowel, if it's in a word, from the list of vowels if you're iterating through that list in code.
Also, if some vowel is not in the word, then using break, you can immediately finish going through the rest of the vowels.
And make the variable names more understandable. For example, not 'i' but 'word', or not 'm' but 'vowel'. It will be easier for you to read your code and not get confused in it, and to other people :)

CodePudding user response:

for word in ("rahul", "aeiou"):
    if all(vowel in word for vowel in "aeiou"):
        print(word)
  • Related