-1

So assuming I've already defined a function called vowel_call that draws out only the vowels from a string, how do I integrate this function into another function called nonvowels to return a string of only nonvowels from a general string?

def nonvowels (word: str) -> str:
   result = ''
   for x in word:
    if vowel_call(x) == False:
        result = result + x
        return result
assert nonvowels('book') == 'bk'
assert nonvowels('giraffe') == 'grff'

I tried the code without the assert statements, and Python only gives back the first nonvowel of the phrase: (nonvowels('genie') = 'g'), but not 'gn'. With the assert statements, an error is produced. What should I do to fix the code?

Deer530
  • 73
  • 1
  • 1
  • 10

4 Answers4

0

Your function returns too early. Reduce the indent on the return statement to be outside the loop

T3 H40
  • 2,326
  • 8
  • 32
  • 43
0

Is your return statement inside of your if statement? If it is, could that be your problem for returning only the first non vowel letter? And does the vowel_call method return false only when the letter is not a vowel? Check out the first suggestion, if that's not your problem, let me know.

theCJCsoccer
  • 601
  • 8
  • 29
0

You are returning inside the loop the first time if vowel_call(x) == False evaluates to True, you would need to move your return outside the loop after you have checked every char in the string.

def nonvowels (word: str) -> str:
   result = ''
   for x in word:
       if vowel_call(x) == False:
           result = result + x
   return result # outside loop

But the simplest method is to return a list comprehension with str.join:

def nonvowels (word: str) -> str:
   return "".join([x for x in word if not vowel_call(x)])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0
You can also with set operations find what you need.

sentence = 'It is a nice day!'

def find_vowels(s,):
import re
s = s.lower()
return set(re.findall(r'[aoiue]',s))

>>>find_vowels(sentence)
{'a', 'e', 'i'}

s_sentence = set(sentence.lower())

>>>non_vowels = s_sentence - find_vowels(sentence) - set(string.punctuation) - set(string.whitespace)

{'c', 'y', 'n', 't', 's', 'd'}
LetzerWille
  • 5,355
  • 4
  • 23
  • 26