интригующий вопрос. Как вращать строку, игнорируя определенные символы?
Здесь мы удаляем, вращаем, вставляем символов.
Дано
import collections as ct
def index(s):
"""Return a reversed dict of (char, [index, ...]) pairs."""
dd = ct.defaultdict(list)
for i, x in enumerate(s):
dd[x].append(i)
return dd
s1 = "The intern"
s2 = "Hello world!"
Код
def rotate(s, n=0, ignore=""):
"""Return string of rotated items, save ignored chars."""
s0 = s[:]
# Remove ignored chars
for ig in ignore:
s = s.replace(ig, "")
# Rotate remaining string, eqiv. to `res = s[-n:] + s[:-n]`
tail = s[-n:]
head = ""
for c in s[:-n]:
head += c
res = tail + head
# Reinsert ignored chars
if ignore:
res = list(res)
lookup = index(s0)
for ig in ignore:
for idx in lookup[ig]:
res.insert(idx, ig)
res = "".join(res)
return res
Тесты
assert rotate(s1, n=0, ignore="") == "The intern"
assert rotate(s1, n=1, ignore="") == "nThe inter"
assert rotate(s1, n=1, ignore=" ") == "nTh einter"
assert rotate(s1, n=3, ignore=" ") == "ern Theint"
assert rotate(s2, n=12, ignore="") == "Hello world!"
assert rotate(s2, n=1, ignore="") == "!Hello world"
assert rotate(s2, n=1, ignore="H !") == "Hdell oworl!"
assert rotate(s2, n=1, ignore="!") == "dHello worl!"