
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Program to check the string is repeating string or not in Python
- Golang Program to check a string contains a specified substring or not
- Program to check a string is palindrome or not in Python
- Program to check given string is pangram or not in Python
- Python program to check if a string is palindrome or not
- Python program to check if the string is empty or not
- How to check whether a String contains a substring or not?
- Program to check given string is anagram of palindromic or not in Python
- Program to check whether two string arrays are equivalent or not in Python
- Program to check string is palindrome with lowercase characters or not in Python
- Program to check string is palindrome or not with equivalent pairs in Python
- Python program to check whether a given string is Heterogram or not
- Python program to check if a given string is Keyword or not
- Program to check typed string is for writing target string in stuck keyboard keys or not in Python
- Check if a binary string contains consecutive same or not in C++
