Sorted? yes? no? how? ..in Python

The challenge

Complete the method which accepts an array of integers, and returns one of the following:

  • "yes, ascending" – if the numbers in the array are sorted in an ascending order
  • "yes, descending" – if the numbers in the array are sorted in a descending order
  • "no" – otherwise

You can assume the array will always be valid, and there will always be one correct answer.

Complete the method which accepts an array of integers, and returns one of the following:

  • "yes, ascending" – if the numbers in the array are sorted in an ascending order
  • "yes, descending" – if the numbers in the array are sorted in a descending order
  • "no" – otherwise

You can assume the array will always be valid, and there will always be one correct answer.

The solution in Python code

Option 1:

def is_sorted_and_how(arr): asc = sorted(arr) desc = sorted(arr, reverse=True) if arr==asc: return "yes, ascending" elif arr==desc: return "yes, descending" else: return "no"
Code language: Python (python)

Option 2:

def is_descending(arr): for i in range(len(arr) - 1): if arr[i + 1] > arr[i]: return False return True def is_ascending(arr): for i in range(len(arr) - 1): if arr[i + 1] < arr[i]: return False return True def is_sorted_and_how(arr): if is_ascending(arr): return 'yes, ascending' if is_descending(arr): return 'yes, descending' return 'no'
Code language: Python (python)

Option 3:

is_sorted_and_how = lambda a: ['no','yes, ascending','yes, descending'][(sorted(a)==a)+(sorted(a)[::-1]==a)*2]
Code language: Python (python)

Test cases to validate our solution

test.it("[1, 2]") test.assert_equals(is_sorted_and_how([1, 2]), 'yes, ascending') test.it("[15, 7, 3, -8]") test.assert_equals(is_sorted_and_how([15, 7, 3, -8]), 'yes, descending') test.it("[4, 2, 30]") test.assert_equals(is_sorted_and_how([4, 2, 30]), 'no')
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments