Program to get final string after shifting characters with given number of positions in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s and another list of integers called shifts whose length is same as the length of s. Here each element in shifts[i] indicates it to shift the first i + 1 letters of s by shifts[i] positions. If shifting crosses 'z' it will be wrap up to 'a'. We have to find the resulting string after applying shifts to s.

So, if the input is like s = "tomato" shifts = [2, 5, 2, 3, 7, 4], then the output will be "qjcoes" so, after shifting first character 2 places, it will be 't' to 'v', so string is "vomato", After that first two characters 5 places. the string now will be "atmato" like that finally the string will be "qjcoes".

To solve this, we will follow these steps −

• start := ASCII of "a"
• res := a list of the ASCII of (i - start) for each i in s
• for i in range size of shifts - 2 to 0, decrease by 1, do
• shifts[i] := shifts[i] + shifts[i + 1]
• for i in range 0 to size of s - 1, do
• c :=(res[i] + shifts[i]) mod 26
• res[i] := character with ASCII (c + start)
• join the letters res into a string and return

Example

Let us see the following implementation to get better understanding −

def solve(s, shifts):
start = ord("a")
res = [ord(i) - start for i in s]

for i in range(len(shifts) - 2, -1, -1):
shifts[i] += shifts[i + 1]

for i in range(len(s)):
c = (res[i] + shifts[i]) % 26
res[i] = chr(c + start)

return "".join(res)

s = "tomato"
shifts = [2, 5, 2, 3, 7, 4]
print(solve(s, shifts))

Input

[2, 1], 3, 2

Output

qjcoes
Updated on 16-Oct-2021 10:21:11