Issue
- Whenever a capital 'M' is encountered, duplicate the previous character (then remove the 'M')
- 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))
Solution
Use re.sub
like so:
import re
strings = ['abcNdgM', 'abcdg', 'MrtyNNgMM']
for s in strings:
# Repeat the cycles of transforming M/N with previous or subsequent characters:
while True:
s_new = re.sub(r'N.', '', re.sub(r'(.)M', r'\1\1', s))
if s == s_new:
break
s = s_new
# Remove any remaining Ms and Ns:
s = re.sub(r'[MN]+', '', s)
print(s)
# abcgg
# abcdg
# rtyggg
r'STRING'
: raw string.
.
: any 1 character.
\1
: capture group 1, that is, whatever was matched by the pattern inside the parentheses.
Answered By - Timur Shtatland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.