Comments by "Dr Gamma D" (@DrDeuteron) on "5 Ways To Improve Any Function in Python" video.
-
since the str object offers isdigit(), isalpha(), isalphanum() functions, which all follow a well known python builtin pattern, I would create my own version for vowels, which is:
>>>isvowel = 'aeiouAEIOUàáâäǎæãåāaèéêëěẽēėęìíîïǐĩīıįòóôöǒœøõōùúûüǔũūűű'._contains_
From there, summing booleans is a trick. A violation of POLA (principle of least astonishment), so I agree, it's gotta go. We are NOT summing, we are COUNTING, so call a well known count method:
>>>return list(map(isvowel, text)).count(True)
That is tight, with zero "if" blocks and zero loops. Minimum cyclomatic complexity. No (implicit) casting bools to int, just counting True's in a list. Clear as day.
But, maybe too compact, so comment your code:
try
# create mapper to check is vowel
is_vowel_map = map(isvowel, text)
except TypeError as err:
raise [some message] from err
# check each character's vowel status
check_list = list(is_vowel_map)
# count isvowel == True in check_list
vowel_count = check_list.count(True)
return vowel_count
1