Finds the most cost efficient sequence for converting one string into another. >>> costs, operations = compute_transform_tables("cat", "cut", 1, 2, 3, 3) >>> costs[0][:4] [0, 3, 6, 9] >>> costs[2][:4] [6, 4, 3, 6] >>> operations[0][:4] ['0', 'Ic', 'Iu', 'It']
(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
)
| 10 | |
| 11 | |
| 12 | def compute_transform_tables( |
| 13 | source_string: str, |
| 14 | destination_string: str, |
| 15 | copy_cost: int, |
| 16 | replace_cost: int, |
| 17 | delete_cost: int, |
| 18 | insert_cost: int, |
| 19 | ) -> tuple[list[list[int]], list[list[str]]]: |
| 20 | """ |
| 21 | Finds the most cost efficient sequence |
| 22 | for converting one string into another. |
| 23 | |
| 24 | >>> costs, operations = compute_transform_tables("cat", "cut", 1, 2, 3, 3) |
| 25 | >>> costs[0][:4] |
| 26 | [0, 3, 6, 9] |
| 27 | >>> costs[2][:4] |
| 28 | [6, 4, 3, 6] |
| 29 | >>> operations[0][:4] |
| 30 | ['0', 'Ic', 'Iu', 'It'] |
| 31 | >>> operations[3][:4] |
| 32 | ['Dt', 'Dt', 'Rtu', 'Ct'] |
| 33 | |
| 34 | >>> compute_transform_tables("", "", 1, 2, 3, 3) |
| 35 | ([[0]], [['0']]) |
| 36 | """ |
| 37 | source_seq = list(source_string) |
| 38 | destination_seq = list(destination_string) |
| 39 | len_source_seq = len(source_seq) |
| 40 | len_destination_seq = len(destination_seq) |
| 41 | costs = [ |
| 42 | [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) |
| 43 | ] |
| 44 | ops = [ |
| 45 | ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) |
| 46 | ] |
| 47 | |
| 48 | for i in range(1, len_source_seq + 1): |
| 49 | costs[i][0] = i * delete_cost |
| 50 | ops[i][0] = f"D{source_seq[i - 1]}" |
| 51 | |
| 52 | for i in range(1, len_destination_seq + 1): |
| 53 | costs[0][i] = i * insert_cost |
| 54 | ops[0][i] = f"I{destination_seq[i - 1]}" |
| 55 | |
| 56 | for i in range(1, len_source_seq + 1): |
| 57 | for j in range(1, len_destination_seq + 1): |
| 58 | if source_seq[i - 1] == destination_seq[j - 1]: |
| 59 | costs[i][j] = costs[i - 1][j - 1] + copy_cost |
| 60 | ops[i][j] = f"C{source_seq[i - 1]}" |
| 61 | else: |
| 62 | costs[i][j] = costs[i - 1][j - 1] + replace_cost |
| 63 | ops[i][j] = f"R{source_seq[i - 1]}" + str(destination_seq[j - 1]) |
| 64 | |
| 65 | if costs[i - 1][j] + delete_cost < costs[i][j]: |
| 66 | costs[i][j] = costs[i - 1][j] + delete_cost |
| 67 | ops[i][j] = f"D{source_seq[i - 1]}" |
| 68 | |
| 69 | if costs[i][j - 1] + insert_cost < costs[i][j]: |
no outgoing calls
no test coverage detected