2

It (should, to me,) say True if there are only vowels in the string(phrase); otherwise says False. I don't understand why it always will return False, since (x >= x) always returns True. I thank anyone for checking the solution to this query.

(str) -> bool

def valid_letter_sequence(abc):

    valid_letters = abc.count('A') + abc.count('E') + abc.count('I') + abc.count('O') + abc.count('U')
    counted_letters = abc.count('')
    if valid_letters >= counted_letters:
        return True
    else:
        return False
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56

2 Answers2

6

Observe:

>>> 'abc'.count('')
4

Passing an empty string to count gives you one more than the length of the string (because it finds the empty string at both ends as well as between every pair of characters). Why don't you just use len(abc)?

More generally, there are better ways to do what you're doing. Like maybe this:

def valid_letter_sequence(abc):
    return not (set(abc) - set('AEIOU'))
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Certainly It's easier to use `len(abc)`and unfortunately didn't know that detail on `count`. Your comment sure was useful and will vote you up as soon as I get the reputation to do so. I'm always trying to shorten my codes and your feedback is surely enlightening. Thank you. – Gary J. Espitia S. Oct 16 '12 at 06:02
1

You should of course be using len() to find the length of abc. Another disadvantage of count() is that it needs to scan the string again. Python already knows the length, so it's more efficient to just ask for it.

all allows the function to return as soon as it encounters a character not in "AEIOU". This is known as short circuit evaluation

def valid_letter_sequence(abc):
    return all(x in "AEIOU" for x in abc)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502