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
Selected Reading
Python Program to extracts elements from a list with digits in increasing order
When it is required to extract elements from a list with digits in increasing order, a simple iteration, a flag value and the str method is used. This technique helps identify numbers where each digit is larger than the previous one.
Example
Let's extract numbers that have digits in strictly increasing order ?
my_list = [4578, 7327, 113, 3467, 1858]
print("The list is :")
print(my_list)
my_result = []
for element in my_list:
my_flag = True
for index in range(len(str(element)) - 1):
if str(element)[index + 1] <= str(element)[index]:
my_flag = False
if my_flag:
my_result.append(element)
print("The result is :")
print(my_result)
Output
The list is : [4578, 7327, 113, 3467, 1858] The result is : [4578, 3467]
How It Works
The algorithm checks each number digit by digit:
- 4578: 4 < 5 < 7 < 8 ? (increasing)
- 7327: 7 > 3 ? (not increasing)
- 113: 1 = 1 ? (not strictly increasing)
- 3467: 3 < 4 < 6 < 7 ? (increasing)
- 1858: 8 > 5 ? (not increasing)
Alternative Approach Using List Comprehension
Here's a more concise version using list comprehension ?
numbers = [4578, 7327, 113, 3467, 1858]
def has_increasing_digits(num):
digits = str(num)
return all(digits[i] < digits[i + 1] for i in range(len(digits) - 1))
result = [num for num in numbers if has_increasing_digits(num)]
print("Original list:", numbers)
print("Numbers with increasing digits:", result)
Original list: [4578, 7327, 113, 3467, 1858] Numbers with increasing digits: [4578, 3467]
Conclusion
Both approaches convert numbers to strings and compare consecutive digits. The flag-based method is more explicit, while list comprehension with all() provides a cleaner, more Pythonic solution for filtering numbers with strictly increasing digits.
Advertisements
