1

Write a program that receives a string and shifts all the vowels present in it to the beginning.

I have tried sorting the vowels one by one and removing them on the go and saving the two strings separately,then at the end i joined it

s = "You love Python!"
vowels = "aeiou"
s1= ""
for l in range(0,len(s)):
    if s[l] in vowels:
        s1 = s1+s[l]
        s2 = s.replace(s[l],"")

print(s1+s2)

OUTPUT :

ouoeoYu lve Pythn!

But in output "e" in second word is not sorted. What is the error?

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
Prawal Dey
  • 11
  • 1

1 Answers1

3

Problem:

The reason your code does not quite work is because you sometimes use s and sometimes s2. s.replace(s[l],"") does nothing to s - so every time you use it, s2 gets to be s with one vowel replaced in it - the others vowels are taken as isfor s.

The last vowel replaced is o - so s2 becomes: Yu lve Pythn! - u and e are still in it.

Your code fixed:

s = "You love Python!"
vowels = "aeiou"
s1 = ""
for c in  s:
    if c in vowels:
        s1 = s1+c                  # produces new string every time
        s = s.replace(c,"")        # produces new string every time

print(s1+s) # ouoeoY lv Pythn!

Optimizations:

Do not iterate by index, iterate over the characters of a string directly. If you collect things from strings, avoid producing more strings, use a list instead. Strings are immuteable, every time you modify one it is constructed new.

Suboptimal: You can use list comprehensions to get the chars into two lists, combine both lists and join them back into a string:

s = "You love Python!"

s1 = [x for x in s if x.lower() in "aeiou"] # gets vowels, order and capitalization is kept
s2 = [x for x in s if x.lower() not in "aeiou"]  # gets all other characters

s3 = ''.join(s1+s2)  # adds lists back together and makes it a continious string

print(s1)
print(s2)
print(s3)

Output:

['o', 'u', 'o', 'e', 'o']
['Y', ' ', 'l', 'v', ' ', 'P', 'y', 't', 'h', 'n', '!']
ouoeoY lv Pythn!

Disadvantage: you have to go over the whole string twice. A simple for loop can do it in one pass:

s = "You love Python!"

s1=[]
s2=[]
for c in s:
    if c in "aeiou":
        s1.append(c)
    else:
        s2.append(c)

s3 = ''.join(s1+s2)
print(s1)
print(s2)
print(s3)

Output is the same.


Doku:

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57