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
# Python3 code to demonstrate working of
# Test if String is Monotonous
# Using list comprehension + map() + split()
# initializing string
test_str = "6, 5, 4, 3, 2, 1"
# printing original string
print("The original string is : " + test_str)
# initializing delim
delim = ", "
# Test if String is Monotonous
# Using list comprehension + map() + split()
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))
# printing result
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
# Python3 code to demonstrate working of
# Test if String is Monotonous
# Using map() + split() + zip() + len()
# initializing string
test_str = "6, 5, 4, 3, 2, 1"
# printing original string
print("The original string is : " + test_str)
# initializing delim
delim = ", "
# Test if String is Monotonous
# Using map() + split() + zip() + len()
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)
# printing result
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
# Python3 code to demonstrate working of
# Test if String is Monotonous
# initializing string
test_str = "6, 5, 4, 3, 2, 1"
# printing original string
print("The original string is : " + test_str)
# initializing delim
delim = ", "
# Test if String is Monotonous
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
# Printing the result
print("Is string Monotonous ? : " + str(res))
OutputThe 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
# inpput list
s = "6, 5, 4, 3, 2, 1"
# Print the answer
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
# Python3 code to demonstrate working of
# Test if String is Monotonous
# initializing string
test_str = "6, 5, 4, 3, 2, 1"
# printing original string
print("The original string is : " + test_str)
# initializing delimiter
delim = ", "
# Convert string to list of integers
temp = list(map(int, test_str.split(delim)))
# Check if list is monotonically increasing or decreasing
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))
# Check if the list is monotonous
is_monotonous = is_increasing or is_decreasing
# printing result
print("Is string Monotonous ? : " + str(is_monotonous))
OutputThe 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
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 si
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() MethodPython# Python code to check if string is numeric
6 min read
Find Length of String in Python 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. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
2 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
Python - Convert None to empty string In Python, it's common to encounter None values in variables or expressions. In this article, we will explore various methods to convert None into an empty string.Using Ternary Conditional OperatorThe ternary conditional operator in Python provides a concise way to perform conditional operations wit
2 min read