1

write a python function so that

words at odd position:reverse it

words at even position:rearrange the characters so that all consonants appear before the vowels and their order should not change

input:the sun rises in the east output:eht snu sesir ni eht stea

I have reverse the string but unable to do the rearrangement of characters. Can we use append and join function or need to swap at end. Basically rotation of string is done so how we can acheive that.

def encrypt_sentence(sentence):
    vowel_set = set("aeiouAEIOU")
    final_list=[]
    word=sentence.split()
    for i in range(0,len(word)):
        if((i%2)==0):
            final_list.append(word[i][::-1])
        else:
           final_list.append("".join(c for c in word if c not in vowel_set))
 print(final_list)                   
encrypt_sentence("the sun rises in the east")   
Tanya Chaudhary
  • 95
  • 1
  • 4
  • 13

3 Answers3

2

I would iterate through the letters keeping track of the vowels and consonants, and then use join at the end.

def encrypt_sentence(sentence):
    vowel_set = set("aeiouAEIOU")
    final_list=[]
    word=sentence.split()
    for i in range(0,len(word)):
        if((i%2)==0):
            final_list.append(word[i][::-1])
        else:  # do rearrangement
            vowels = list()
            consonants = list()
            for letter in word[i]:
                if letter in vowel_set:
                    vowels.append(letter)
                else:
                    consonants.append(letter)
            new_string = "".join(consonants) + "".join(vowels)
            final_list.append(new_string)
    return final_list
Andrew McDowell
  • 2,860
  • 1
  • 17
  • 31
1

try using two list comprehensions:

word='testing'
vov=[x if x in vowel_set else '' for x in word]
cons=[x if x not in vowel_set else '' for x in word]
('').join(cons+vov)
MaxS
  • 978
  • 3
  • 17
  • 34
0
def encrypt_sentence(sentence):
    vowel=set("AEIOUaeiou")
    s1=sentence
    var=""

    li = list(sentence.split(" "))
    for i in range(len(li)):
        var=li[i]
        if(i%2==0):
            var=var[::-1]
            li[i]=var

        else:
            t=""
            t2=""
            for j in var:
                if(j in vowel):
                    t2=t2+j
                else:
                    t=t+j
            t=t+t2
            li[i]=t
    var2=""
    for i in range(len(li)):
        var2=var2+li[i]
        if(i != len(li)-1):
            var2=var2+" "
    return var2


sentence="The sun rises in the east"
encrypted_sentence=encrypt_sentence(sentence)
print(encrypted_sentence)