Header Ads Widget

string Transformation | hackerrank certification solution

 Program :-

There is a sentence that consists of space- separated strings of upper and lower case English letters. Transform each string according to the given algorithm and return the new sentence.

Each string should be modified as follows:

• The first character of the string remains unchanged 

• For each subsequent character, say x, consider a letter preceding it, say y

  • If y precedes x in the English alphabet, transform x to uppercase
  • If x precedes y in the English alphabet, transform x to lowercase 
  • If x and y are equal, the letter remains unchanged

Sample Input 0

a Blue MOON

Sample Output 0

a BLUE MOON

Explanation 

The input sentence is "a Blue MOON". The first letters of all words remain unchanged. Then, for the word the "I" is made uppercase because the letter preceding it, "b", comes earlier in the alphabet. Next, the "u" becomes uppercase because the letter preceding it, "I", comes earlier in the alphabet. Finally, the "e" remains lowercase because the letter preceding it comes later in the alphabet. For the second word, "MOON", only its last letter, "n", changes to lower case because the letter preceding it comes later in the alphabet.

Code(Python):-

import math
import os
import random
import re
import sys


def transformSentence(sentence):
# Write your code here
l=sentence.split()
ans=""
for i in range(len(l)):
j=0
s=""
length=len(l[i])

while(j<length):
if j==0:
s+=l[i][j]
j+=1
continue
a=l[i][j].lower()
b=l[i][j-1].lower()
if a>b:
s+=(a.upper())
elif a<b:
s+=(a.lower())
else:
s+=l[i][j]
j+=1
l[i]=s
ans=" ".join(l)
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
sentence = input()
result = transformSentence(sentence)
fptr.write(result + '\n')
fptr.close()



Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments