Python | Test if String is Monotonous
Last Updated :
01 May, 2023
Sometimes, while working with Python strings, we can have a problem in which we have a string and we wish to check if a string is consecutively increasing or decreasing. This kind of problem has applications in both data and day-day programming. Let us discuss certain ways in which this problem can be solved.
Method #1: Using map() + split() + list comprehension
The combination of the above functions can be used to perform this task. In this, we split the string to list, separated by delim, and then for the monotonous list problem test we employ list comprehension.
Python3
test_str = "6, 5, 4, 3, 2, 1"
print ( "The original string is : " + test_str)
delim = ", "
temp = list ( map ( int , test_str.split(delim)))
direc = temp[ - 1 ] > temp[ 0 ] or - 1
res = temp = = list ( range (temp[ 0 ], temp[ - 1 ] + direc, direc))
print ( "Is string Monotonous ? : " + str (res))
|
Output :
The original string is : 6, 5, 4, 3, 2, 1
Is string Monotonous ? : True
Time complexity: O(n) where n is the length of the string.
Auxiliary space: O(n) where n is the length of the string.
Method #2: Using map() + split() + zip() + len()
The combination of the above functions can be used to perform this task. In this, we perform the task of split as above, but the task of performing the monotonous is done by zip() and len().
Python3
test_str = "6, 5, 4, 3, 2, 1"
print ( "The original string is : " + test_str)
delim = ", "
temp = list ( map ( int , test_str.split(delim)))
diff = set (i - j for i, j in zip (temp, temp[ 1 :]))
res = len (diff) = = 1 and diff.pop() in ( 1 , - 1 )
print ( "Is string Monotonous ? : " + str (res))
|
Output :
The original string is : 6, 5, 4, 3, 2, 1
Is string Monotonous ? : True
Method #3: Using map(),split() and sort() methods
Python3
test_str = "6, 5, 4, 3, 2, 1"
print ( "The original string is : " + test_str)
delim = ", "
temp = list ( map ( int , test_str.split(delim)))
x, y = [], []
x.extend(temp)
y.extend(temp)
res1, res2, res = False , False , False
temp.sort()
if (temp = = x):
res1 = True
temp.sort(reverse = True )
if (temp = = y):
res2 = True
if (res1 or res2):
res = True
print ( "Is string Monotonous ? : " + str (res))
|
Output
The original string is : 6, 5, 4, 3, 2, 1
Is string Monotonous ? : True
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(nlogn)
Auxiliary Space : O(n)
Method 4: Using for loop
The function takes a string of numbers separated by commas and checks if it is monotonous (i.e., each number is less than or equal to the previous number). It does this by first converting the string into a list of integers. Then, it uses a for loop to iterate through the list and check if each element is greater than the previous element. If any element is greater than the previous element, it returns False. If the loop completes without returning False, it returns True.
Algorithm:
- Convert the given string into a list of integers.
- Use a for loop to iterate through the list and check if each element is less than or equal to the previous element.
- If any element is greater than the previous element, return False.
- If the loop completes without returning False, return True.
Python3
def is_monotonous(s):
nums = [ int (x) for x in s.split( ", " )]
for i in range ( 1 , len (nums)):
if nums[i] > nums[i - 1 ]:
return False
return True
s = "6, 5, 4, 3, 2, 1"
print (is_monotonous(s))
|
Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), where n is the length of the string.
Approach #5: Using all() and any() with List Comprehension
Algorithm:
- Convert the given string into a list of integers using map() and split().
- Check if the list is monotonically increasing by checking if each element in the list is less than or equal to the next element.
- Check if the list is monotonically decreasing by checking if each element in the list is greater than or equal to the next element.
- Use all() to check if any of the above two conditions are true.
- Print the result.
Python3
test_str = "6, 5, 4, 3, 2, 1"
print ( "The original string is : " + test_str)
delim = ", "
temp = list ( map ( int , test_str.split(delim)))
is_increasing = all (temp[i] < = temp[i + 1 ] for i in range ( len (temp) - 1 ))
is_decreasing = all (temp[i] > = temp[i + 1 ] for i in range ( len (temp) - 1 ))
is_monotonous = is_increasing or is_decreasing
print ( "Is string Monotonous ? : " + str (is_monotonous))
|
Output
The original string is : 6, 5, 4, 3, 2, 1
Is string Monotonous ? : True
Time complexity: O(n)
Auxiliary space: O(n) (for creating the temporary list)
Similar Reads
Longest String in list - Python
We are given a list of strings, and our task is to find the longest string present in the list. If there are multiple strings with the maximum length, we should return the first one that appears. For example, given a = ["alpha", "gamma", "epsilon", "delta"], the longest string is "epsilon". Let's di
2 min read
Python - Test if Substring occurs in specific position
Sometimes, while working with python strings, we can have a problem in which we need to test occurrence of substring. There is straight forward way to test this. But sometimes, we have a more specific problem in which we need to test if substring occurs at that particular position. Let's discuss cer
6 min read
Check if String is Empty or Not - Python
We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example: Using Comparison Operator(==)The s
2 min read
Python Check If String is Number
In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number. Example: Using isdigit() Method [GFGTABS] Python # Python code to check if strin
6 min read
Python - Test if string contains element from list
Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
3 min read
Python - Words Lengths in String
We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6]. Using Lis
2 min read
Python - Test substring order
Given two strings, check if substring characters occur in correct order in string. Input : test_str = 'geeksforgeeks', K = 'sees' Output : True Explanation : "s" after that "ee" and then "s" is present in order in string 1. Input : test_str = 'geeksforgeeks', K = 'seef' Output : False Explanation :
5 min read
Word location in String - Python
Word location in String problem in Python involves finding the position of a specific word or substring within a given string. This problem can be approached using various methods in Python, such as using the find(), index() methods or by regular expressions with the re module. Using str.find()str.f
4 min read
Python - Test for strictly decreasing list
The test for a monotonic sequence is a utility that has manifold applications in mathematics and hence every sphere related to mathematics. As mathematics and Computer Science generally go parallel, mathematical operations such as checking for strictly decreasing sequences can be useful to gather kn
5 min read
Find length of a string in python (6 ways)
In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. [GFGTABS] Python a = "geeks" print(len(a)) [/GFGTABS]Output5 Using for loop and 'in' operatorA string can be iterate
2 min read