简体   繁体   English

检查列表是升序还是降序(使用 FOR)

[英]Check if list is Ascending OR Descending (using FOR)

So I have been set a task in my college where I'm suppose to check whether a list is in fact sorted (either ascending or descending).所以我在我的大学里被设置了一个任务,我想检查一个列表是否实际上是排序的(升序或降序)。 But I MUST use 'for'.但我必须使用'for'。 (We just recently learned about for and lists and we must practice it) (最近刚学了for和list,一定要实践一下)

This is what I have so far, I am able to confirm if a list is descending, but not descending OR ascending:到目前为止,这是我所拥有的,我能够确认列表是否正在降序,但不是降序或升序:

A=[10,9,8,3,1,0]

def order(A):
    for i in range(len(A) - 1): 
        if ((A[i]>A[i+1])) :
            return False
    return True

You need to create an algorithm in a such way so that the result before the other parameter, is unique!您需要以这种方式创建一个算法,以便其他参数之前的结果是唯一的!

For ascending, check if the subtraction between the current item and the next time is greater than 0, if so, it is not sorted ascending.对于升序,检查当前项与下一次的减法是否大于0,如果是,则不升序排序。

For descending, check if the subtraction between the current item and the next time is lesser than 0, if so, it is not sorted descending.对于降序,检查当前项与下一次的减法是否小于0,如果是,则不进行降序排序。

Try this:试试这个:

def order(A) # Ascending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] > 0:
            return False
    return True

def order(A) # Descending order
    for i in range(len(A) - 1):
        if A[i] - A[i+1] < 0:
            return False
    return True

Here is a simple way to return whether the list is ascending, descending, or neither.这是一个简单的方法来返回列表是升序、降序还是两者都不是。

def order(A):
if A == sorted(A,reverse=False):
    return 'Ascending'
elif A == sorted(A,reverse=True):
    return 'Descending'
else:
    return 'Neither'

Here is a sample output with simple input.这是一个带有简单输入的示例输出。

>> a = [2,5,4,7,1]
>> b = [1,3,5,7,9]
>> c = [9,6,3,1,0]
>> print(order(a), order(b), order(c))
out: Neither Ascending Descending

The benefit of this function is that we don't have to analyze the individual elements, we simply have to use built-in functions to analyze the list as a whole.这个函数的好处是我们不必分析单个元素,我们只需要使用内置函数来分析整个列表。

This might help:这可能有帮助:

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))

and when executed, this code's output was:执行时,此代码的输出为:

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

Here what we are doing is that we are maintaining two boolean flags asc and desc , which will represent whether the list passed was in ascending order or descending order.这里我们要做的是维护两个布尔标志ascdesc ,它们将表示传递的列表是升序还是降序。

Then for each consecutive pair of numbers in the list, we calculate their difference if someList[idx] - someList[idx - 1] >= 0: then we and desc flag with False and vice versa in the else case.然后,对于每个连续的一对列表中的号码,计算它们的差if someList[idx] - someList[idx - 1] >= 0:然后我们和desc标志与False ,反之亦然在else情况下。

Intuitively, what is being done in this code is as follows: if a sequence is in ascending order, then every consecutive pair of numbers will have their difference greater than zero, for ex: consider this sequence [a, b, c, d, e, f] where all characters represent numbers and assume for the case when this sequence is in ascending order ie a <= b <= c <= d <= e <= f and if we consider all the consecutive pairs of numbers ie (a, b), (b, c), (c, d), and so on.. and calculate difference for each of those pairs ie ba, cb, dc and so on.. then every difference will be >= 0 ie ba >= 0 and cb >= 0 and dc >= 0 and ed >= 0 and fe >= 0 and this is the condition that is being represented by the asc boolean flag in the code above.直观地说,这段代码的作用是这样的:如果一个序列是升序的,那么每对连续的数字都会有它们的差大于零,例如:考虑这个序列[a, b, c, d, e, f]其中所有字符都表示数字并假设此序列按升序排列,即a <= b <= c <= d <= e <= f ,如果我们考虑所有连续的数字对,即(a, b), (b, c), (c, d), and so on..并计算这些对中的每一个的差异,即ba, cb, dc and so on..那么every difference will be >= 0ba >= 0 and cb >= 0 and dc >= 0 and ed >= 0 and fe >= 0这是上面代码中asc布尔标志表示的条件。 Similar explanation can be thought for desc boolean flag.可以对desc布尔标志进行类似的解释。

And if you want a smaller version of the code above while still using for loop then use this:如果您在仍然使用for循环的同时想要上述代码的较小版本,请使用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))

and output for this并为此输出

descending order
ascending order
ascending order
no order
no order
no order

You want to return True if the list is ascending or descending .如果listascendingdescending您想返回True

This makes the code really *readable**:这使得code真正*可读**:

def order(lst):
    ascending = descending = True
    for i in range(len(lst) - 1): 
        if lst[i] > lst[i+1] :
            ascending = False
        elif lst[i] < lst[i+1] :
            descending = False
    return ascending or descending

We start by defining 2 boolean variables set to True - ascending and descending .我们首先定义2 boolean variables设置为True - ascendingdescending We then loop through the lst (I gave the function a more sensible param name) and check if this index is less than the next.然后,我们通过循环lst (我给了function更明智的param名)和检查ifindex小于下。 If it is, we can set the ascending variable to False (as the lst can now no longer be ascending). Else, if the next index is greater than the current如果是,我们可以将ascending variable设置为False (因为lst现在不能再ascending). Else, if the next index is greater than the current ascending). Else, if the next index is greater than the current index , we set descending to False`. ascending). Else, if the next index is greater than the current索引, we set降序, we set to False`。

Then finally, at the end we return if either the lst was ascending or descending .最后,最后我们return如果lstascending or descending


Some examples:一些例子:

>>> order([1,2,3,4])
True
>>> order([1,2,3,2])
False
>>> order([3,2,1,0])
True
>>> order([3,2,1,4])
False

Hope this helps!希望这有帮助! (by the way, if your interested, you could literally do the same function in one-line ): (顺便说一句,如果您有兴趣,您可以在one-line执行相同的function ):

def order(lst):
    return lst == sorted(lst) or lst == sorted(lst)[::-1]
def descending(l):
  x=0
  if len(l)<= 1 or (len(l) == 2 and l[0] >= l[1]):
    return True
  else:
    if l[0]<=l[1]:
      return descending(l[1:])
    else:
      return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM