Sorted? sure? no? how? ..in Python

[ad_1]

The problem

Full the tactic which accepts an array of integers, and returns one of many following:

  • "sure, ascending" – if the numbers within the array are sorted in an ascending order
  • "sure, descending" – if the numbers within the array are sorted in a descending order
  • "no" – in any other case

You may assume the array will all the time be legitimate, and there’ll all the time be one appropriate reply.

Full the tactic which accepts an array of integers, and returns one of many following:

  • "sure, ascending" – if the numbers within the array are sorted in an ascending order
  • "sure, descending" – if the numbers within the array are sorted in a descending order
  • "no" – in any other case

You may assume the array will all the time be legitimate, and there’ll all the time be one appropriate reply.

The answer in Python code

Choice 1:

def is_sorted_and_how(arr):
    asc = sorted(arr)
    desc = sorted(arr, reverse=True)
    if arr==asc:
        return "sure, ascending"
    elif arr==desc:
        return "sure, descending"
    else:
        return "no"

Choice 2:

def is_descending(arr):
    for i in vary(len(arr) - 1):
        if arr[i + 1] > arr[i]: return False
    return True

def is_ascending(arr):
    for i in vary(len(arr) - 1):
        if arr[i + 1] < arr[i]: return False
    return True
   
def is_sorted_and_how(arr):
    if is_ascending(arr): return 'sure, ascending'
    if is_descending(arr): return 'sure, descending'
    return 'no'

Choice 3:

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

Check circumstances to validate our answer

check.it("[1, 2]")
check.assert_equals(is_sorted_and_how([1, 2]), 'sure, ascending')

check.it("[15, 7, 3, -8]")
check.assert_equals(is_sorted_and_how([15, 7, 3, -8]), 'sure, descending')

check.it("[4, 2, 30]")
check.assert_equals(is_sorted_and_how([4, 2, 30]), 'no')

[ad_2]

Leave a Reply