Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Enumeration Indexing (annotated) solution in Clear category for Revorse the vewels by BootzenKatzen
def reverse_vowels(text: str) -> str:
letters = list(text) # Turning the text into a list of characters
vowels = [] # creating an empty list for our vowels
for index, char in enumerate(letters): # enumerating our letter list to easily get indexes
if char in "aeiouAEIOU": # if the letter is a vowel
vowels.append((char, index)) # add it and its index as a tuple to the vowel list
while len(vowels) > 1: # while there are two or more vowel index pairs on the list
# (if it's only 1, it's in the middle and won't be swapped)
letters[vowels[0][1]] = vowels[-1][0] # the letter at the first vowel's index is now the last vowel
letters[vowels[-1][1]] = vowels[0][0] # and the letter at the last vowel's index is now the first one
vowels = vowels[1:-1] # remove the pairs from either end of the list
for i in range(len(text)): # iterate through each letter of the original text
if text[i].isupper(): # if the letter is uppercase
letters[i] = letters[i].upper() # make sure the letter on the list is uppercase
if text[i].islower(): # if it's lowercase
letters[i] = letters[i].lower() # make sure the list letter is lowercase
return "".join(letters) # return the rejoined list
print("Example:")
print(reverse_vowels("Hello, World"))
# These "asserts" are used for self-checking
assert reverse_vowels("Bengt Hilgursson") == "Bongt Hulgirssen"
assert (
reverse_vowels("Why do you laugh? I chose death.")
== "Why da yee loigh? U chasu dooth."
)
assert (
reverse_vowels("These are the people you protect with your pain!")
== "Thisa uro thi peoplu yoe protect weth year peen!"
)
print("The mission is done! Click 'Check Solution' to earn rewards!")
Dec. 12, 2023
Comments: