Determine if list is ascending, descending, or neither without built-ins
Here is a possible solution:
ascending = True
descending = True
prev_index = 0
for index in range(1, len(list1)):
ascending = ascending and list1[index] >= list1[prev_index]
descending = descending and list1[index] <= list1[prev_index]
prev_index = index
if ascending:
print("Elements are arranged in ascending order")
elif descending:
print("Elements are arranged in descending order")
else:
print("Elements are not arranged in any order")
When all the elements of a list are equal (for example, list1 = [1,1,1]
), both ascending and descending are True
: in my solution the list is considered to be ascending.
How to find if the elements in a list are in ascending order or in descending order without using sort function?
def which_order(list1):
isAscending = True
isDescending = True
for i in range(1,len(list1)):
if(list1[i] >= list1[i-1]):
isDescending = False
elif(list1[i] <= list1[i-1]):
isAscending = False
if((not isAscending) and (not isDescending)):
print("The list is not sorted in either order.")
break
if(isAscending):
print("The list is sorted in ascending order.")
if(isDescending):
print("The list is sorted in descending order.")
Sample output:
list1 = [1,2,3,4]
list2 = [9,8,7,6]
list3 = [1,9,8,7,6]
which_order(list1)
which_order(list2)
which_order(list3)
The list is sorted in ascending order.
The list is sorted in descending order.
The list is not sorted in either order.
Check if list is sorted in either ascending or descending order in one pass
You could check pairs of consecutive elements, keep track of whether the first pair that is not ==
is <
or >
, and check that all the other pairs have the same relation (if not equal):
def is_sorted(lst):
asc = None
for i in range(len(lst)-1):
a, b = lst[i], lst[i+1]
if a == b:
continue
if asc is None:
asc = (a < b)
if (a < b) != asc:
return False
return True
That's a bit verbose, but you could also make it shorter with next
and all
, using a shared zip
iterator for both so the entire list is iterated only once.
def is_sorted(lst):
pairs = zip(lst, lst[1:])
asc = next((a < b for a, b in pairs if a != b), None)
return asc is None or all((a < b) == asc for a, b in pairs if a != b)
However, this version (like your original) will create a copy of the input list with lst[1:]
, so that's not really just a single loop, either. To fix that, you could e.g. use itertools.tee
or islice
.
Checking if an Array is in Ascending or Descending order in a loop
Here is a way to determine if all three are in descending order, ascending order, or not in order at all.
1. Scanner scanner = new Scanner(System.in);
2. int[] heights = new int[3];
3. heights[0] = scanner.nextInt();
4. heights[1] = scanner.nextInt();
5. heights[2] = scanner.nextInt();
6.
7. if (heights[0] >= heights[1] && heights[1] >= heights[2]) {
8. System.out.println("descending order");
9. } else if (heights[0] <= heights[1] && heights[1] <= heights[2]) {
10. System.out.println("ascending order");
11. } else {
12. System.out.println("not in order");
13. }
A few notes:
- line 2: this is hard-coded to 3, obviously it wouldn't work if you want to compare with 4 or some other number
- lines 3-5: also hard-coded to 3, but easily could be moved into a loop
- line 7: if item 0 is larger than 1, and 1 is larger than 2, that's clearly "descending". This could be reworked to fit with a loop, but it's perhaps clearer to see this way.
- line 9: similar to 7, just compare the other direction
- line 12: this is the case for mixed ordering, neither ascending nor descending
If you want to use a loop, here's an edit to replace lines 2-5:
int totalToCheck = 3;
int[] heights = new int[totalToCheck];
for (int i = 0; i < totalToCheck; i++) {
heights[i] = scanner.nextInt();
}
Check a list if sorted in ascending or descending or not sorted in haskell?
A problematic part of your function is the | otherwise = Descending
. According to your function definition, if there are two consecutive examples in the list such that x >= y
, then the function is descending. This is not True
: a function is descending if for all two consecutive elements x > y
(or x >= y
if you do not require it to be strictly descending).
Furthermore an additional problem here is that a list with one element (or no elements) can be seen as both Ascending
and Descending
. So I think the first thing we have to do is define some semantics. We can decide to make the output a list of TypeOfSort
items, or we can decide to extend the number of options of TypeOfSort
.
In this answer I will pick the last option. We can extend TypeOfSort
to:
data TypeOfSort = Ascending | Descending | Both | NotSorted
deriving (Show)
Now we can work on the function itself. The base cases here are of course the empty list []
and the list with one element [_]
:
sorted [] = Both
sorted [_] = Both
Now we need to define the inductive case. When is a list sorted ascendingly? If all elements are (strictly) larger than the previous element. Analogue a list is sorted descending if all elements are (strictly) smaller than the previous element. Let us for now assume strictness. It is easy to alter the function definition later.
So in case we have a list with two or more elements, a list is Ascending
if the list that starts with the second element is Ascending
or Both
, and x < y
, or in other words:
sorted (x:y:xs) | Both <- sort_yxs, x < y = Ascending
| Ascending <- sort_yxs, x < y = Ascending
where sort_yxs = sorted (y:xs)
The same holds for descending order: if the rest of the list is in descending order, and the first element is greater than the second, then the list is in descending order:
| Both <- sort_yxs, x > y = Descending
| Ascending <- sort_yxs, > y = Descending
where sort_yxs = sorted (y:xs)
In all the remaining cases, it means that some part(s) of the list are Ascending
and some part(s) are Descending
, so then the list is NotSorted
.
| otherwise = NotSorted
or putting these all together:
sorted [] = Both
sorted [_] = Both
sorted (x:y:xs) | Both <- sort_yxs, x < y = Ascending
| Ascending <- sort_yxs, x < y = Ascending
| Both <- sort_yxs, x > y = Descending
| Ascending <- sort_yxs, x > y = Descending
| otherwise = NotSorted
where sort_yxs = sorted (y:xs)
Refactoring: make TypeOfSort
a Monoid
The above definition contains a lot of edge cases, this makes it hard to write a simple program. We can make it easier by introducing some utility functions. This can for instance be done by defining a function that takes two TypeOfSort
s and then returns the intersection. Such a function could look like:
intersect Both x = x
intersect x Both = x
intersect Ascending Ascending = Ascending
intersect Descending Descending = Descending
intersect _ _ = NotSorted
This actually forms a monoid with Both
as identity element:
instance Monoid where
mappend Both x = x
mappend x Both = x
mappend Ascending Ascending = Ascending
mappend Descending Descending = Descending
mappend _ _ = NotSorted
mempty = Both
Now we can rewrite our definition as:
sorted [] = Both
sorted [_] = Both
sorted (x:y:ys) | x > y = mappend rec Ascending
| x < y = mappend rec Descending
| otherwise = NotSorted
where rec = sorted (y:ys)
Check if array values are ascending or descending
You could use a check for two elements in advance and select a comparison function and check all elements with Array#every
. This allows to use a short circuit if a previous element and the actual element does not match the expected order.
Then return the type of the order or the message, that the array is not ordered.
function check(array) { var direction = array[0] < array[1] ? { type: 'asc', fn: (a, b) => a < b } : { type: 'desc', fn: (a, b) => a > b };
return array.every((v, i, a) => !i || direction.fn(a[i - 1], v)) ? direction.type : 'no';}
console.log([[15, 7, 3, -8], [4, 2, 30], [1, 2, 3]].map(check));
How to check if an array of string is sorted Ascending/Descending alphabetically?
You can iterate over the array and track the results of String#localeCompare()
called on all neighbors.
Then simply check if all results are either <= 0
or >=0
and return 'ascending' or 'descending' accordingly, otherwise return 'unsorted'.
function getSortDirection(arr) {
const c = [];
for (let i = 1; i < arr.length; i++) {
c.push(arr[i - 1].localeCompare(arr[i]));
}
if (c.every((n) => n <= 0)) return 'ascending';
if (c.every((n) => n >= 0)) return 'descending';
return 'unsorted';
}
const ascending = ['apple', 'summer', 'sun', 'zoo'];
const descending = ['zoo', 'sun', 'summer', 'apple'];
const unsorted = ['summer', 'zoo', 'apple', 'sun'];
console.log(ascending, '–', getSortDirection(ascending));
console.log(descending, '–', getSortDirection(descending));
console.log(unsorted, '–', getSortDirection(unsorted));
Related Topics
Vscode: There Is No Pip Installer Available in the Selected Environment
Stripping Whitespaces from a List Inside the List of Tuples
How to Repeat a Function N Times
In Python, How to Check If a String Only Contains Certain Characters
Sort Array and Return Original Indexes of Sorted Array
Beautifulsoup: Get the Contents of a Specific Table
How to Create a Common Function to Execute a Python Script in Jenkins
How to Wait Until I Receive Data Using a Python Socket
Typeerror: Strptime() Argument 1 Must Be Str, Not List
Python Pip Install Error [Ssl: Certificate_Verify_Failed]
How to Correct Typeerror: Unicode-Objects Must Be Encoded Before Hashing
How to Increase the Font Size of the Markdown Table in Jupyter Notebook
Calculate Rgb Value for a Range of Values to Create Heat Map
Regex to Match Digits and At Most One Space Between Them
How to Change the File Name of an Uploaded File in Django
How to Get Max() to Return Variable Names Instead of Values in Python