0

For this code I pretty much have it so that it will return certain indices, but it counts multiple vowels in the same index. I just realized that index() only returns the first occurrence of the item, but now I've pretty much exhausted other possibilities.

def vowel_indices(s):
'string ==> list(int), return the list of indices of the vowels in s'
res = []
for vowel in s:
    if vowel in 'aeiouAEIOU':
        res = res + [s.index(vowel)]
return res

An example of this working is:

vowel_indices('hello world')

[1, 4, 7]

Instead I end up getting [1,4,4] as the return.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
iKyriaki
  • 589
  • 4
  • 14
  • 26

2 Answers2

4

Use a list comp with enumerate:

vowel_indices = [idx for idx, ch in enumerate(your_string) if ch.lower() in 'aeiou']
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

Your problem is that .index() stops at the first occurrence of your vowel, so duplicate vowels that come later don't get noticed.

Instead of using .index(), use a counter variable (sort of like a C++ for loop):

def vowel_indices(s):
    res = []
    index = 0

    for vowel in s:
        index += 1

        if vowel.lower() in 'aeiou':
            res.append(index)

    return res

Or use enumerate():

def vowel_indices(s):
    res = []

    for index, vowel in enumerate(s):
        if vowel.lower() in 'aeiou':
            res.append(index)

    return res
Blender
  • 289,723
  • 53
  • 439
  • 496