Home > front end >  Performing double letter swap operations
Performing double letter swap operations

Time:04-05

I want to change the letters in my input. To do this I have implemented a dictionary that works for a singular letter. However, I want to have a different output if there is a "double-letter". For example, "text" should be returned with "rexr", which it does. But for "textt", I would want it to return "rexss". Below is the attached code. Any tips?

vowels = {
    "t" : "r",
    "r" : "s",
    "s" : "b",
    "b" : "t",
    "T" : "R",
    "R" : "S",
    "S" : "B",
    "B" : "T",
    "tt" : "ss",
    "rr" : "bb",
    "ss" : "rr",
    "bb" : "tt",
    "TT" : "SS",
    "RR" : "BB",
    "SS" : "TT",
    "BB" : "RR"
}

inputString = input()

outputString = ""

for character in inputString:

    if character in vowels: 
        outputString  = vowels[character]
    else:
        outputString  = character

print(outputString)

CodePudding user response:

You can use a regex for that. Ensure you craft the regex starting with the longest strings so that 'tt' matches before 't':

inputString = 'text textt'

import re

regex = '|'.join(map(re.escape, sorted(vowels, key=len, reverse=True)))
# 'tt|rr|ss|bb|TT|RR|SS|BB|t|r|s|b|T|R|S|B'

re.sub(regex, lambda x: vowels.get(x.group()), inputString)

output: 'rexr rexss'

CodePudding user response:

If you want to incrementally construct the result, you can use a while loop with string slicing. A for loop wouldn't easily work here, because you don't know how many characters to skip over for each iteration.

user_input = input()
result_characters = []

idx = 0
while idx != len(user_input):
    if user_input[idx:idx   2] in vowels:
        result_characters.append(vowels[user_input[idx:idx   2]])
        idx  = 2
    else:
        result_characters.append(vowels.get(user_input[idx], user_input[idx]))
        idx  = 1

print(''.join(result_characters))
  • Related