How to create a class in which letters from array 1 will turn into letters from the second

Viewed 27

I have two arrays

w = ["t", "k", "p"]
w2 = ["т", "к", "п"]

should work

In: "kpt"
Out: "кпт" 
1 Answers

I would use a dictionary instead of lists.

So I would first define a dictionary that would map my letters correctly like:

letter_mapping = {
"t": "т",
"k": "к",
"p": "п"
}

then, I can make a function that uses this dictionary to translate my words:

def translate(word: str) -> str:
    translation = ""
    for letter in word:
        translation += letter_mapping[letter]
    return translation

Now if you pass a test like print(translate('tkp')) you will get ткп back.


[Update]

If you absoloutly have to use list then I would do something like:

w = ["t", "k", "p"]
w2 = ["т", "к", "п"]

def translate(word:str)->str:
    if len(w) != len(w2):
        raise RuntimeError('Two lists dont have matching lengths!')

    translation = ""
    for letter in word:
        translation += w2[w.index(letter)]
    return translation

However, I have to mention that in this approach, you have to make sure per letter added to list w you have to add its translation in the exact same position in w2. If the order of translation in the second list doesn't match the order of letters in first list, this will give you a wrong translation.

Related