Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to replace all digits with characters using Python
Suppose we have an alphanumeric string that contains lowercase English letters in its even positions and digits in its odd positions. We need to perform a shift operation where each digit at odd position i gets replaced with the character obtained by shifting the letter at position i-1 by the digit value.
The shift operation works as follows: shift('p', 5) = 'u' and shift('a', 0) = 'a'. For every odd index i, we replace the digit s[i] with shift(s[i-1], s[i]).
Problem Example
If the input is s = "a2b1d4f3h2", then the output will be "acbcdhfihj" because ?
shift('a', 2) = 'c'shift('b', 1) = 'c'shift('d', 4) = 'h'shift('f', 3) = 'i'shift('h', 2) = 'j'
Algorithm
To solve this, we will follow these steps ?
Initialize an empty result string
-
For each character in the string:
If the character is a digit, replace it with the shifted character
Otherwise, keep the character as is
Return the result string
Implementation
def solve(s):
result = ""
for i in range(len(s)):
if s[i].isdigit():
# Shift the previous character by the digit value
result += chr(int(s[i]) + ord(s[i-1]))
else:
# Keep the letter as is
result += s[i]
return result
# Test the function
s = "a2b1d4f3h2"
output = solve(s)
print(f"Input: {s}")
print(f"Output: {output}")
Input: a2b1d4f3h2 Output: acbcdhfihj
How It Works
The solution uses ASCII values to perform character arithmetic. When we encounter a digit at position i, we:
Get the ASCII value of the previous character using
ord(s[i-1])Add the digit value using
int(s[i])Convert back to character using
chr()
Step-by-Step Trace
For input "a2b1d4f3h2" ?
Position 0: 'a' − keep as 'a'
Position 1: '2' − shift('a', 2) = chr(97 + 2) = 'c'
Position 2: 'b' − keep as 'b'
Position 3: '1' − shift('b', 1) = chr(98 + 1) = 'c'
Position 4: 'd' − keep as 'd'
Position 5: '4' − shift('d', 4) = chr(100 + 4) = 'h'
Conclusion
This algorithm efficiently replaces digits with shifted characters using ASCII arithmetic. The time complexity is O(n) where n is the length of the string, making it an optimal solution for this character shifting problem.
