Program to check string contains consecutively descending string or not in Python



Suppose we have a string s with some digits, we have to check whether it contains consecutively descending integers or not.

So, if the input is like s = "99989796", then the output will be True, as this string is holding [99,98,97,96]

To solve this, we will follow these steps−

  • Define a function helper() . This will take pos, prev_num

  • if pos is same as n, then

    • return True

  • num_digits := digit count of prev_num

  • for i in range num_digits - 1 to num_digits, do

    • if s[from index pos to pos+i-1] and numeric form of s[from index pos to pos+i-1]) is same as prev_num - 1, then

      • if helper(pos + i, prev_num - 1), then

      • return True

    • return False

    • From the main method, do the following−

    • n := size of s

    • for i in range 1 to quotient of n/2, do

      • num := numeric form of s[from index 0 to i-1]

      • if helper(i, num) is true, then

      • return True

    • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution: def solve(self, s):    n = len(s)    def helper(pos, prev_num):    if pos == n:       return True    num_digits = len(str(prev_num))    for i in range(num_digits - 1, num_digits + 1):       if s[pos:pos+i] and int(s[pos:pos+i]) == prev_num - 1:          if helper(pos + i, prev_num - 1):             return True       return False    for i in range(1, n//2 + 1):       num = int(s[:i])    if helper(i, num):       return True    return False ob = Solution() s = "99989796" print(ob.solve(s))

Input

"99989796"

Output

True
Updated on: 2020-10-05T14:42:50+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements