Python Check if list is sorted
To check if a list is sorted using Python, you can create your own algorithmic logic or use the already inbuilt Python function all();
1. Using brute force
-------------------------------------------------------------------------------------------------------------
#Output
True
False
1. Using brute force
#Python Check if list is sorted items1 = [5, 7, 8, 9, 10, 11, 23, 34, 54] items2 = [8, 9, 89, 34, 67, 45, 54, 34, 33] def is_sorted(items_list): #Using brute force for i in range(0, len(items_list) - 1): if items_list[i] > items_list[i + 1]: return False return True print(is_sorted(items1)) print(is_sorted(items2))
-------------------------------------------------------------------------------------------------------------
#Output
True
False
2. Using all method
#Check if list is sorted using Python inbuilt method def is_sorted_python(items_list): return all(items_list[i] <= items_list[i + 1] for i in range(len(items_list) - 1)) print(is_sorted_python(items1)) print(is_sorted_python(items2))
-------------------------------------------------------------------------------------------------------------
#Output
True
False
Comments
Post a Comment