分享

python升序数判断

 老三的休闲书屋 2021-04-16

这可能有助于:A=[10,9,8,3,1,0]

B=[1,9,18,33,41,50]

C=[1, 1, 1, 1, 1]

D= [1]

E=[1, 2, 3, 2, 1]

F =[]

def order(someList):

asc = True

desc = True

for idx in range(1, len(someList)):

if someList[idx] - someList[idx - 1] >= 0:

asc = asc & True

desc = desc & False

else:

desc = desc & True

asc = asc & False

if asc and not desc:

return 'list is in ascending order'

elif desc and not asc:

return 'list is in descending order'

else:

return 'list is in no order'

print(order(A))

print(order(B))

print(order(C))

print(order(D))

print(order(E))

print(order(F))

执行时,此代码的输出为:list is in descending order

list is in ascending order

list is in ascending order

list is in no order

list is in no order

list is in no order

这里我们要做的是维护两个布尔标志asc和desc,这两个标志将表示传递的列表是按升序还是降序排列。

然后,对于列表中的每一对连续数字,我们计算它们的差if someList[idx] - someList[idx - 1] >= 0:,然后使用False和desc标记,反之亦然。

直观地说,在这段代码中所做的工作如下:

如果一个序列是按升序排列的,那么每一个连续的数字对之间的差值将大于零,例如:考虑这个序列[a, b, c, d, e, f],其中所有字符都表示数字,假设这个序列是升序的,即a <= b <= c <= d <= e <= f,如果我们考虑所有连续的数字对,即(a, b), (b, c), (c, d), and so on..,并计算每一对的差,即b-a, c-b, d-c and so on..,然后every difference will be >= 0,即b-a >= 0 and c-b >= 0 and d-c >= 0 and e-d >= 0 and f-e >= 0,这是由上面代码中的asc布尔标志表示。对于desc布尔标志也有类似的解释。

如果您希望在使用for循环时使用上述代码的较小版本,请使用:A=[10,9,8,3,1,0]

B=[1,9,18,33,41,50]

C=[1, 1, 1, 1, 1]

D= [1]

E=[1, 2, 3, 2, 1]

F = []

def order(someList):

results = [True if second >= first else False for first, second in zip(someList, someList[1:])]

if any(results) and all(results):

return 'ascending order'

elif not any(results) and not all(results):

return 'descending order'

else:

return 'no order'

print(order(A))

print(order(B))

print(order(C))

print(order(D))

print(order(E))

print(order(F))

以及输出descending order

ascending order

ascending order

no order

no order

no order

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多