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
Python - Remove non-increasing elements
When working with lists, sometimes we need to remove elements that break an increasing sequence. This means keeping only elements that are greater than or equal to the previous element, creating a non-decreasing subsequence.
Understanding Non-Increasing Elements
Non-increasing elements are those that are smaller than the previous element in the sequence. By removing them, we create a monotonically increasing or non-decreasing subsequence.
Method: Using Iteration and Comparison
We can iterate through the list and keep only elements that maintain the increasing order ?
my_list = [5, 23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11]
print("The original list is:")
print(my_list)
# Start with the first element
my_result = [my_list[0]]
# Iterate through remaining elements
for elem in my_list[1:]:
if elem >= my_result[-1]:
my_result.append(elem)
print("The result after removing non-increasing elements:")
print(my_result)
The original list is: [5, 23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11] The result after removing non-increasing elements: [5, 23, 45, 45, 67, 89, 99]
How It Works
The algorithm follows these steps:
- Initialize: Start with the first element in the result list
- Compare: For each subsequent element, compare it with the last element in result
- Keep or Skip: If current element ? last element in result, append it; otherwise skip
- Result: The final list contains only non-decreasing elements
Alternative: Using List Comprehension
We can achieve the same result using a more compact approach ?
my_list = [5, 23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11]
def remove_non_increasing(lst):
if not lst:
return []
result = [lst[0]]
for elem in lst[1:]:
if elem >= result[-1]:
result.append(elem)
return result
filtered_list = remove_non_increasing(my_list)
print("Original:", my_list)
print("Filtered:", filtered_list)
Original: [5, 23, 45, 11, 45, 67, 89, 99, 10, 26, 7, 11] Filtered: [5, 23, 45, 45, 67, 89, 99]
Example with Different Data
Let's see how this works with a different sequence ?
numbers = [1, 3, 2, 4, 3, 5, 7, 6, 8, 9]
print("Original numbers:", numbers)
result = [numbers[0]]
for num in numbers[1:]:
if num >= result[-1]:
result.append(num)
print("Non-decreasing subsequence:", result)
print("Removed elements:", [x for x in numbers if x not in result or numbers.count(x) > result.count(x)])
Original numbers: [1, 3, 2, 4, 3, 5, 7, 6, 8, 9] Non-decreasing subsequence: [1, 3, 4, 5, 7, 8, 9] Removed elements: [2, 3, 6]
Conclusion
Removing non-increasing elements creates a monotonically non-decreasing subsequence. This technique is useful for data filtering and maintaining sorted order in sequences.
