I am doing some exercises in a Python course, and one of them where I am stuck is below:
Given a digit sequence that represents a message where each uppercase letter
is replaced with a number (A - 1, B - 2, ... , Z - 26) and space - 0.
Find the number of the initial messages, from which that sequence
could be obtained.
Example: 12345 - 3 (ABCDE, LCDE, AWDE)
11 - 2 (AA, K)
The naive solution is easy and it is a simple brute force algorithm:
import string
def count_init_messages(sequence):
def get_alpha(seq):
nonlocal count
if len(seq) == 0:
count += 1
return
for i in range(1, len(seq) + 1):
if seq[:i] not in alph_table:
break
else:
get_alpha(seq[i:])
alphabet = " " + string.ascii_uppercase
alph_table = {str(n): alph for n, alph in zip(range(len(alphabet)), alphabet)}
count = 0
get_alpha(sequence)
return count
def main():
sequence = input().rstrip()
print(count_init_messages2(sequence))
if __name__ == "__main__":
main()
But since the length of the input sequence can reach 100 characters, and there can be many repetitions, I met time limits. For example, one of the sample input 2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129). Since my implementation does too many repetitions, it takes age to process such input. I am thinking about using a backtracking algorithm, but I have not yet figured out how to implement memoirization for successful results.
I would be glad if you can point me to the right path, how to break this task.