在python中给我的问题是:接受一个具有n个术语的列表,并在不使用sort函数和def的情况下检查元素是否按升序,降序排列。
请帮助我执行此程序。
代码:
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")
答案 0 :(得分:2)
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.
答案 1 :(得分:1)
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