Let us suppose we have given a string in this form.
xstr = 'hewBllo'
Where each B represents how many previous characters will be deleted from the string. For instance, the above string contains 1 B. Thus, the first letter previous to B will be deleted from the string. The new string should look like this.
new_xstr = 'hello'
Another example:
xstr = 'remoBBBising'
after the transformation, the new string should look like this,
new_xstr = 'rising'
Since there are 3 B letters starting from the first B previous three letters should be deleted from the string. I have come up with an algorithm, but it takes too long for such a seemingly small process. Can you guys think of 1-2 lines of code that can do this process or maybe an intelligent way to do it?
My algorithm:
1-Read the script from behind.
2-When you first encountered B, start counting.
3-When you reach end of B stop counting.
4-Delete the strings as the count.
5-Delete all B letters.
Using a regex replacement with a lambda callback we can try:
str = 'remoBBBising'
output = re.sub(r'(\w+?)(B+)', lambda m: m.group(1)[:-len(m.group(2))] , str)
print(output) # rising
The logic here is to capture, in two separate groups, both the B term along with the preceding word leading up to it. Then, we replace with just the first captured word, trimming it from the end by the length of the B term.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With