Alternately Sorted

... by Bittle in Programming Help January 09, 2021

Question:

A logical recursive function should be written that gets a list of integers and checks whether the members with equal indicators are arranged in descending order, and the members with odd indexes are sorted in ascending order.

To test the functionality, write an initial function that receives from the user the length of the list and then the end members, a basic function that receives from the user the length of the end members.

Order not by rotation if the error is repeated.


Examples:

[2, 18, 3, 15, 3, 9, 7, 4]

alternately sorted

[2, 18, 3, 15, 3, 9, 7, 14]

not alternately sorted


Answer:

def alternatively_sorted(in_list):
    if len(in_list) <= 2:
        # base case, 2 or less items are sorted
        return True
    else:
        if len(in_list) > 3 and in_list[3] > in_list[1]:
            # has next even, but even is not descending
            return False


        if in_list[2] < in_list[0]:
            # odd is not ascending
            return False


        return alternatively_sorted(in_list[2:])  # remove first 2 elements




if __name__ == '__main__':
    len_ = int(input("Enter length of list: "))
    l_in = input("Enter list elements separated by commas (2, 4, 5, 7, 10, ...): ")
    l_in = [int(x.strip()) for x in l_in.split(",")]  # split by comma and remove extra space around with strip()
    a = alternatively_sorted(l_in)
    if len_ != len(l_in):
        print("Lengths are incorrect!")
    else:
        # lengths are good
        print(len_, l_in, a)
        # test cases
        b = alternatively_sorted([2, 18, 3, 15, 3, 9, 7, 4])
        c = alternatively_sorted([2, 18, 3, 15, 3, 9, 7, 14])


        print(b, c)


Comments (0)

Search Here