Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python Code to Count Possible Decoding Of A Given Digit Sequence

Count Possible Decoding

Count Possible Decoding Of A Given Digit Sequence

Python Code to Count Possible Decoding of a Given Digit Sequence returns the number of decodings possible for a string. Here decodings must be a valid English alphabet. Check below example for better understanding

  • String=”127″ , possible decodings are
    • 1,2,7
    • 12,7

In the above example 27 is not a valid decoding as highest number possible is 26 which is “z”.

Algorithm:

  • Step 1: Start
  • Step 2: User is required to insert a digit sequence as an input
  • Step 3: Set count = 0
  • Step 4: If the last number is not a zero, then return for the next remaining (n-1) numbers and add the results then to the total count.
  • Step 5: If the last two digits form a valid variable (or smaller than 27), return for the remaining (n-2) numbers and add the outcome to the total calculation.
  •  Step 6: Stop

Python Code:

def cnt_decoding_digitsdig,a):
    cnt=[0]*(a+1)
    cnt[0], cnt[1]= 11
    for k in range(2,a+1):
        cnt[k] = 0
        cnt[k] = cnt[k-1]
        if (dig[k-2] == ‘1’ or (dig[k-2] == ‘2’ and dig[k-1] < ‘7’) ):
            cnt[k] += cnt[k-2]
    return cnt[a]

 

print(cnt_decoding_digits(“127”,3))

Output:

2