Home > other >  A python function to shift the positions of a vowel by 2 places?
A python function to shift the positions of a vowel by 2 places?

Time:11-07

r task is to shift the vowels by two positions contained in the string, where vowels are the symbols a e i o u (and their capitalised versions A E I O U), If the input is "a cat", the output is "i cit"

vowels = ["a", "e", "i", "o", "u"]
vowel=['a','e','i','o','u']

mapper = dict(zip(vowels, vowels[1:]   [vowels[0]]))
message=input('enter mesaage')

new_message = ""
for letter in message:
    if letter not in vowels:
        new_message  = letter
    else:
        i = vowels.index(letter)
        i =2
        new_message  = vowels[i]
print(new_message)

this throws an index out of bound error

CodePudding user response:

vowels = ["a", "e", "i", "o", "u", "a", "e", "i", "o", "u"]

message=input('enter mesaage')

new_message = ""
for letter in message:
    if letter not in vowels:
        new_message  = letter
    else:
        i = vowels.index(letter)
        i =2
        new_message  = vowels[i]
print(new_message)

This gives me maad for mood if that is what you wanted

CodePudding user response:

You need a function count_repetition which tells you how many consecutive vowels there are starting at any position. This is also the number of vowels in vowels array that you should skip. The new vowel can be found using vowels[(steps i 1)%size] where size is the length of vowels array and i is the index of the original vowel.

vowels = ["a", "e", "i", "o", "u"]

def count_repetition(message, i):
    # counts the number of consecutive chars starting at index i
    count = 1;
    for j in range(i,len(message)-1):
        if(message[j]==message[j 1]):
            count =1
        else:
            return count
    return count

message=input('enter message: ')
new_message = ""
size= len(vowels)
j=0

while(j<len(message)):
    letter = message[j]
    if letter.lower() not in vowels:
        new_message  = letter
        j =1
    else:
        i = vowels.index(letter)
        steps = count_repetition(message, j) # count number of consecutive letters
        for _ in range(0,steps):
            new_message  = vowels[(steps i 1)%size]
        j =steps
        
print(new_message)
# meeduuu -> muudooo
# a cat -> i cit
# meed -> muud
# maad -> mood
  • Related