Program to find number of ways we can decode a message in Python

ProgrammingPythonServer Side Programming

Suppose we have mapping like 'a' = 1, 'b' = 2, ... 'z' = 26, and we have an encoded message message string, we have to count the number of ways it can be decoded.

So, if the input is like message = "222", then the output will be 3, as This can be decoded 3 ways: bbb, bv, and vb.

To solve this, we will follow these steps −

  • memo := a list of 0s of size same as message size + 1

  • memo[0] := 1

  • memo[1] := 1 when message[0] is not same as "0" otherwise 0

  • for i in range 2 to size of message, do

    • n1 := numeric value of message[from index i-1 to i]

    • n2 := numeric value of message[from index i-2 to i]

    • n1_valid:= true when n1 > 0

    • n2_valid:= true when n2 > 9 and n2 < 27

    • if n1_valid is true, then

      • memo[i] := memo[i] + memo[i-1]

    • if n2_valid is true, then

      • memo[i] := memo[i] + memo[i-2]

  • return last element of memo

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, message):
      memo = [0 for i in range(len(message)+1)]
      memo[0] = 1
      memo[1] = 1 if message[0]!="0" else 0

      for i in range(2,len(message)+1):
         n1 = int(message[i-1:i])
         n2 = int(message[i-2:i])

         n1_valid= n1>0
         n2_valid= n2>9 and n2<27

         if n1_valid:
            memo[i]+=memo[i-1]
         if n2_valid:
            memo[i]+=memo[i-2]
      return memo[-1]
ob = Solution()
message = "2223"
print(ob.solve(message))

Input

"2223"

Output

5
raja
Published on 07-Oct-2020 11:30:59
Advertisements