Jun-12-2020, 08:22 PM
Here's my preferred solution:
I avoid some particular things for some particular reasons...
I avoided count() because it has to be called for each vowel, causing a multiplication when calculating such algoritms' runtimes. I used a set because they're constant-time lookup, and usually fast; if I really cared about the speed, I'd test to see if a linear search through the string is faster. And if my manager has told me to speed it up I'd check tuples too :)
I avoid map() in Python because I think comprehensions are clearer, and because I think map() should be a method rather than a global function. (This is one place Scala beats Python in my mind. In Python, nesting comprehensions or map calls sucks. But
I avoided len() because it requires creating an intermediate collection. sum() can be passed a generator expression which uses constant-time memory.
vowels = set("aeiou") sum(char in vowels for char in s)This takes advantage of Python letting you sum() booleans. I think it reads like English and is Pythonic. (In a larger program, I'd probably name VOWELS as a constant.)
I avoid some particular things for some particular reasons...
I avoided count() because it has to be called for each vowel, causing a multiplication when calculating such algoritms' runtimes. I used a set because they're constant-time lookup, and usually fast; if I really cared about the speed, I'd test to see if a linear search through the string is faster. And if my manager has told me to speed it up I'd check tuples too :)
I avoid map() in Python because I think comprehensions are clearer, and because I think map() should be a method rather than a global function. (This is one place Scala beats Python in my mind. In Python, nesting comprehensions or map calls sucks. But
collection.map(foo).map(bar).map(baz)
can be spread across multiple lines nicely, if the functions are are defined in-line.)I avoided len() because it requires creating an intermediate collection. sum() can be passed a generator expression which uses constant-time memory.