Попарно заменить буквы в строке

Рейтинг: 4Ответов: 5Опубликовано: 03.05.2023

Есть задание из "TTAGCGCA", вывести "AATCGCGT" используя словарь ретрансляции. Как это сделать?

table = {
    "A": "T",
    "T": "A",
    "C": "G",
    "G": "C"
}

print(list(table.keys()))

Ответы

▲ 7Принят

str.maketrans создаёт таблицу трансляции, str.translate её применяет:

table = {
    "A": "T",
    "T": "A",
    "C": "G",
    "G": "C"
}

trans = str.maketrans(table)
print("TTAGCGCA".translate(trans))
$ python translate.py
AATCGCGT
▲ 4

Естественно неправильный, потому что вы выводите ключи, а не заменяйте символы на другие:

def translate(target: str, dictionary: dict[str, str]) -> str:
    return ''.join(map(lambda x: dictionary.get(x, x), target))

table = {
    "A": "T",
    "T": "A",
    "C": "G",
    "G": "C",
}

print(translate("TTAGCGCA", table))

UPD: Можно сделать так, как сказал @Stanislav Volodarskiy:

def translate(target: str, dictionary: dict[str, str]) -> str:
    return ''.join(target.translate(str.maketrans(table)))
▲ 2

Самый простой вариант:

table = {
    "A": "T",
    "T": "A",
    "C": "G",
    "G": "C"
}

new_str = ''
for l in 'TTAGCGCA':
    new_str += table[l]
print(new_str)

Выводит:

AATCGCGT
▲ 2

Ещё короткий вариант:

table = {
    "A": "T",
    "T": "A",
    "C": "G",
    "G": "C"
}

print(*map(table.get, "TTAGCGCA"), sep='')
# AATCGCGT
▲ 2

Словарь - это неспортивно, надо в нём рыться, искать ;)

s = 'ACGT'
rep = ''.join([chr(846807841//ord(c)%191) for c in s])
print(rep)