Как определить, находятся ли элементы в списке в порядке возрастания или в порядке убывания без использования функции сортировки? - PullRequest
0 голосов
/ 30 октября 2019

Вопрос, который был задан мне в python, заключается в следующем: принять список с n числом терминов и проверить, находятся ли элементы в порядке возрастания, убывания или нет, без использования функции сортировки и определения тоже.

Пожалуйста, помогите мне в этой программе.

Код:

a=list(input("Enter elements:"))
for i in range(len(a)):
    for j in range(i):
        if a[j]<=a[j+1]:
            print("It is in ascending order")
        elif a[j]>=a[j+1]:
            print("It is in descending order")
        else:
            print("It is not in order")

Ответы [ 2 ]

2 голосов
/ 30 октября 2019
def func(l):
    a_cond = True # considering list is in ascending order
    d_cond = True # # considering list is in descending order

    # checking if for any number my ascending condition false

    for i in range(1,len(l)):
        if not l[i]>l[i-1]:
            a_cond = False
    # if condition not false then return list is ascending
    if a_cond:
        return 'Ascending Order'

    # if condition false then check for descending codition
    for i in range(1, len(l)):
        if not l[i]<l[i-1]:
            d_cond = False
    # check if all number in descending order
    if d_cond:
        return 'Descending order'

    # if above both condition fail, list is in mix order
    return 'Mix Order'



print(func([1,2,3,4,5]))
print(func([5,4,3,2,1]))
print(func([1,2,3,1,2]))

выход

Ascending Order
Descending order
Mix Order
1 голос
/ 30 октября 2019
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.")

Пример вывода:

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...