Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).
Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.
Function signature:
def tr(self, lines: List[str], set1: str, set2: str) -> str:
Example:
Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC" Output: "BAnAnA\nCherry" When printed: BAnAnA Cherry
Python has a built-in helper for exactly this.
str.maketrans(set1, set2) builds a translation table mapping each char in set1 to the corresponding char in set2; line.translate(table) applies it.
The full solution:
class Solution:
def tr(self, lines, set1, set2):
table = str.maketrans(set1, set2)
result = []
for line in lines:
result.append(line.translate(table))
return "\n".join(result)
Free plan: 30 tutor messages. Premium is unlimited.
