October 27, 2025
Input: A string s that contains DNA symbols {A, C, T, G}
Output: String s' where the last occurrence of ‘T’ is replaced with ‘A’
Examples
ATCGT → ATCGATTTT → TTTA (last T becomes A)ACGAA → ACGAA (no T to replace)T → AFormal Components:
Two-Phase Algorithm:
_ → transition to q1Key Feature: Explicit state machine matching formal TM definition
Algorithm (No libraries, no regex):
last_t_index = -1last_t_index = ilast_t_index holds position of last Tlast_t_index == -1, no T exists → return unchangeddna[:last_t_index] + 'A' + dna[last_t_index + 1:]State Diagram


#include <iostream>
#include <algorithm>
#include <cctype>
std::string lower(std::string input) {
std::transform(input.begin(), input.end(), input.begin(),
[](unsigned char character){return std::tolower(character);});
return input;
};
std::string lower_text = lower("ACTGT");
void lastTtoA() {
std::string& input_string = lower_text;
std::reverse(input_string.begin(), input_string.end()); // string reverse so first element is the last
char const& replace_letter = 't';
char const& replace_with = 'a';
std::size_t position = input_string.find(replace_letter);
if(position == std::string::npos) std::cout << "No letter T in the string: ";
if(position != std::string::npos){
input_string.replace(position, 1, 1, replace_with);
}
// The line below replaces every T found in the text
//std::replace(input_string.begin(), input_string.end(), replace_letter, replace_with);
// logic to re-reverse input string
std::string normal_string;
for (int i = input_string.length() - 1; i>= 0; --i) {
normal_string += input_string[i];
}
std::cout << normal_string;
}
int main() {
lastTtoA();
}def test_all_implementations():
test_cases = [
("ATCGT", "ATCGA"), # Basic case
("ACGAA", "ACGAA"), # No T's
("", ""), # Empty string
]
implementations = [
("Turing Machine", turing_lastTtoA),
("Pure Python", lastTtoA_plain),
("Regex Python", lastTtoA_regex)
]
for name, func in implementations:
print(f"\nTesting {name}:")
for input_str, expected in test_cases:
result = func(input_str)
status = "✓" if result == expected else "✗"
print(f" {status} '{input_str}' → '{result}' (expected: '{expected}')")Key Finding: All four implementations (TM, Pure Python, Regex, C++) produce identical outputs for identical inputs
Deterministic Turing Machine: Formal 3-state machine with transition function (q0 → q1 → qhalt, tape operations)
ATCGT⊔ → scan right → scan left → replace T → ATCGAPure Python: We used Loop-based scanning with string slicing reconstruction
Python with Regex: Implemented pattern matching to locate and process the last ‘T’ and transformation to ‘A’
Non-Python Implementation: Implemented algorithm in C++ using string reversal and pattern matching techniques
Result: All implementations produce "ATCGT" → "ATCGA"
Comprehensive Testing: All implementations validated with identical test suites
Theoretical Analysis: LastTtoA is computable and tractable (O(n))
Proofgrammers