why is that str.count('') ≠ (from str.count('A') + str.count('B') + … + str.count('Z'))

点点圈 提交于 2019-12-03 21:55:20

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'))

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!