I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a pro
for i in range(0, len(string)):
if string[i] == vowels[i]:
This actually has a subtler problem than only counting each vowel once - it actually only tests if the first letter of the string is exactly a
, if the second is exactly e
and so on.. until you get past the fifth. It will try to test string[5] == vowels[5]
- which gives an error.
You don't want to use i
to look into vowels
, you want a nested loop with a second index that will make sense for vowels
- eg,
for i in range(len(string)):
for j in range(len(vowels)):
if string[i] == vowels[j]:
count += 1
This can be simplified further by realising that, in Python, you very rarely want to iterate over the indexes into a sequence - the for
loop knows how to iterate over everything that you can do string[0]
, string[1]
and so on, giving:
for s in string:
for v in vowels:
if s == v:
count += 1
The inner loop can be simplified using the in
operation on lists - it does exactly the same thing as this code, but it keeps your code's logic at a higher level (what you want to do vs. how to do it):
for s in string:
if s in vowels:
count += 1
Now, it turns out that Python lets do math with booleans (which is what s in vowels
gives you) and ints - True
behaves as 1
, False
as 0
, so True + True + False
is 2
. This leads to a one liner using a generator expression and sum:
sum(s in vowels for s in string)
Which reads as 'for every character in string
, count how many are in vowels
'.