Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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]
Algorithm
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
Example
Let us see the following implementation to get better understanding ?
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 pos + i <= n and 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
How It Works
The algorithm works by:
Starting with different lengths: It tries different starting numbers by taking substrings of length 1 to n/2
Recursive checking: For each starting number, it recursively checks if the remaining string continues the descending sequence
Flexible digit count: Numbers in the sequence can have different digit counts (e.g., 100, 99, 98)
Additional Example
Let's test with another example ?
ob = Solution()
# Test with different cases
test_cases = ["321", "10987654321", "12345", "100999897"]
for test in test_cases:
result = ob.solve(test)
print(f"String '{test}': {result}")
String '321': True String '10987654321': True String '12345': False String '100999897': True
Conclusion
This solution efficiently checks for consecutively descending integers in a string using recursion and backtracking. The algorithm handles numbers with different digit counts and returns True if any valid descending sequence is found.
