HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Reverse vowels in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stringreversevowels

Problem

What do you think about this solution? I guess there are too many lists...

vowels = "aeiou"

def reverseVowels(string):
    vowels_list = []
    string_list = list(string)

    for index,letter in enumerate(string_list):
        if letter in vowels:
            vowels_list.append(letter)

    reversed_vowels_list = list(reversed(vowels_list))

    new_string_list = list(string_list)
    for index,vowel in enumerate(vowels_list):
        idx_vowel_in_string =  string_list.index(vowel)
        new_string_list[idx_vowel_in_string] = reversed_vowels_list[index]

    print new_string_list

reverseVowels("aupiple")

Solution

You use for index, letter in enumerate(string_list): but don't use the index.
Instead of using string_list.index(vowel) in the second loop you can instead build an index list in the first loop.
And reverse either the index list or the vowels list.
This should have a better time complexity as string_list.index(vowel) seems to be making your code time complexity \$O(n^2)\$.

I'd also change your code to follow PEP8, and remove all the redundant _list parts in your variable names.
As this makes your code easier to read.

Finally I'd return, rather than print, the final list as it makes the code more reusable. And, as Mathias commented, you could also change your return type to a string, as giving a string as input and getting a list of strings as output is a little odd.

VOWELS = set('aeiou')

def reverse_vowels(string):
    string = list(string)
    vowels = []
    indexes = []

    for index, letter in enumerate(string):
        if letter in VOWELS:
            vowels.append(letter)
            indexes.append(index)

    for i, char in zip(indexes, reversed(vowels)):
        string[i] = char

    return ''.join(string)

Code Snippets

VOWELS = set('aeiou')

def reverse_vowels(string):
    string = list(string)
    vowels = []
    indexes = []

    for index, letter in enumerate(string):
        if letter in VOWELS:
            vowels.append(letter)
            indexes.append(index)

    for i, char in zip(indexes, reversed(vowels)):
        string[i] = char

    return ''.join(string)

Context

StackExchange Code Review Q#147356, answer score: 5

Revisions (0)

No revisions yet.