Python - Reverse Shift characters by K
Last Updated :
26 Apr, 2023
Given a String, reverse shift each character according to its alphabetic position by K, including cyclic shift.
Input : test_str = 'bccd', K = 1
Output : abbc
Explanation : 1 alphabet before b is 'a' and so on.
Input : test_str = 'bccd', K = 2
Output : zaab
Explanation : 2 alphabets before b is 'z' (rounded) and so on.
Method : Using maketrans() + upper() + list comprehension + translate() + slicing
In this, we make translation table to each character to its K shifted version using maketrans() and slicing. The upper() is used to handle all the upper case characters, translate() is used to perform translation according to lookup translation table created by maketrans().
Python3
# Python3 code to demonstrate working of
# Reverse Shift characters by K
# using maketrans() + upper() + list comprehension + translate() + slicing
# initializing string
test_str = 'GeeksForGeeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 10
alpha_chars = 'abcdefghijklmnopqrstuvwxyz'
# converted to uppercase
alpha_chars2 = alpha_chars.upper()
# maketrans used for lowercase translation
lower_trans = str.maketrans(alpha_chars, alpha_chars[ -K:] + alpha_chars[ : -K])
# maketrans used for uppercase translation
upper_trans = str.maketrans(alpha_chars2, alpha_chars2[ -K:] + alpha_chars2[ : -K])
# merge lookups
lower_trans.update(upper_trans)
# make translation from lookups
res = test_str.translate(lower_trans)
# printing result
print("The converted String : " + str(res))
OutputThe original string is : GeeksForGeeks
The converted String : WuuaiVehWuuai
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Using ASCII values and modulo arithmetic in python:
Approach: We can use the ASCII values of the characters to shift them by K positions. We can subtract K from the ASCII value of each character and get the corresponding character. If the resulting ASCII value is less than the ASCII value of 'a', we can add 26 to it to get the correct character.
- Initialize an empty string result to store the shifted characters.
- Loop through each character char in the input string test_str.
- Convert the character char to its ASCII value using the ord function.
- Subtract the shift value K from the ASCII value. This will give the ASCII value of the shifted character.
- If the resulting ASCII value is less than the ASCII value of the character 'a', add 26 to it. This is because we want to wrap around to the end of the alphabet if we have shifted past the beginning of the alphabet.
- Convert the shifted ASCII value back to a character using the chr function.
- Append the shifted character to the result string.
- Return the result string containing the shifted characters.
Python3
# Python program for the above approach
# Function to reverse the shift ASCII values
def reverse_shift_ascii(test_str, K):
result = ""
for char in test_str:
ascii_val = ord(char) - K
if ascii_val < ord('a'):
ascii_val += 26
result += chr(ascii_val)
return result
# Driver Code
test_str_1 = 'bccd'
K_1 = 1
test_str_2 = 'bccd'
K_2 = 2
# Example outputs
output_1 = 'abbc'
output_2 = 'zaab'
# Print the results
print("Input: test_str = '{}', K = {}".format(test_str_1, K_1))
print("Output:", reverse_shift_ascii(test_str_1, K_1))
print("Expected output:", output_1)
print("Input: test_str = '{}', K = {}".format(test_str_2, K_2))
print("Output:", reverse_shift_ascii(test_str_2, K_2))
print("Expected output:", output_2)
OutputInput: test_str = 'bccd', K = 1
Output: abbc
Expected output: abbc
Input: test_str = 'bccd', K = 2
Output: zaab
Expected output: zaab
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), since we are creating a new string of length n.
Similar Reads
Reverse Alternate Characters in a String - Python Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read
Python - Right and Left Shift characters in String In string manipulation tasks, especially in algorithmic challenges or encoding/decoding scenarios, we sometimes need to rotate (or shift) characters in a string either to the left or right by a certain number of positions.For example, let's take a string s = "geeks" and we need to perform a left and
3 min read
Python | Append K character N times Sometimes, we wish to manipulate a string in such a way in which we might need to add additional K at the end of string in case of filling the missing bits or any other specific requirement. The solution to this kind of problems is always handy and is good if one has knowledge of it. Letâs discuss c
4 min read
Python - Remove Rear K characters from String List Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
5 min read
Python Program To Remove all control characters In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read