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

1 min read 251 words

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"

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'

Option 3:

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

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')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts