Home > OS >  Capital M is encountered, duplicate previous character (then remove the M), and capital N is encount
Capital M is encountered, duplicate previous character (then remove the M), and capital N is encount

Time:05-26

I am trying to do this exercises but is not working for me in python.

any help?

Whenever a capital M is encountered, duplicate the previous character (then remove the M), and whenever a capital N is encountered remove the next character from the string (then remove the N). All other characters in the string will be lowercase letters. For example: "abcNdgM" should return "abcgg". The final string will never be empty.

def StringChanges(str):
    str2 = []
    list = ""

    for i in str:
        if i == 'M':
            str2.pop(i)
            str -= 1
            i -= 1
        elif i == 'N':
            if i == list - 1:
                str2.pop()
        else:
             str2.append(i)
             list -= 2
             i -= 2
    return ''.join(str2)


str = "oMoMkkNrrN"

print(StringChanges(str))

regards.

CodePudding user response:

Use re.sub like so:

import re
strings = ['abcNdgM', 'abcdg']

for s in strings:
    s = re.sub(r'(.)M', r'\1\1', s)
    s = re.sub(r'N.',   '',      s)
    print(s)

r'STRING': raw string.
. : any 1 character.
\1 : capture group 1, that is, whatever was matched by the pattern inside the parentheses.

CodePudding user response:

In this python code, i is a string, taking on the value of each letter, one at a time, for each iteration through the for loop. But in the cupofprogramming example you linked, i is an integer representing the position (index) of a letter through each iteration of the loop. If you want this code to work with the index of each letter, take a look at how the enumerate() function works.

  • Related