-3
def all_vowels(string):
    if 'a' and 'e' and 'i' and 'o' and 'u' in string:
        return True
    else:
        return False
    
print(all_vowels('​she is your friend'))

Output:
True

Hello, I dont understand why it gives True even though there is no "a" in the string..

blitz1
  • 77
  • 5

1 Answers1

0

Maybe this is what you are looking for -

def all_vowels(string):
    v = {'a', 'e', 'i', 'o', 'u'}
    if set(string.split()).intersection(v)==v:
        return True
    else:
        return False
    
all_vowels('abcd')
#False

all_vowels('aeiou')
#True

This is more efficient that you string search -

  1. This takes an intersection between the set of characters in the string and the set of characters in the list of vowels.
  2. If the intersection is the same, as the set of vowels, then it means the string has all the vowels and it returns True.
  3. This saves u from 2 nested for loops for each string.
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • Can we solve it without using list for this time please? – blitz1 Oct 19 '20 at 11:41
  • edited it, check the solution now – Akshay Sehgal Oct 19 '20 at 11:44
  • Thanks, but cant we solve it with just string operation? I mean I know lists and dictionaries, but is there any way to solve it by just modifying my code slightly? – blitz1 Oct 19 '20 at 11:46
  • I think that by using " 'a' and 'e' and 'i' and 'o' and 'u' in string: " line I make sure that string has all these wovels(a,e,i,o,u) But it gives true, I dont understand why – blitz1 Oct 19 '20 at 11:47
  • u can, but it would take u 2 for loops . if that is the case then its super simple and u can do it easily. This was similar to the interview question i usually ask when hiring "what is the miniumum number of for loops required to find if the string has vowels or not". thats why i shared the solution that doesnt need explicit for loops – Akshay Sehgal Oct 19 '20 at 11:47
  • Is my third comment here wrong? – blitz1 Oct 19 '20 at 11:49
  • Because in operation cant work on multiple variables .. `'a' in 'abcd'` works but not `'a', 'b', 'c' in 'abcd'`. You will need a for loop for that. Or worse, write 5 conditional statements with `and` in between each. – Akshay Sehgal Oct 19 '20 at 11:53
  • 1
    Thanks, I understand now. – blitz1 Oct 19 '20 at 11:55
  • great, glad to help – Akshay Sehgal Oct 19 '20 at 11:56