def order(A) # For ascending
for i in range(len(A) - 1):
if A[i] - A[i+1] > 0:
return False
return True
def order(A) # For descending
for i in range(len(A) - 1):
if A[i] - A[i+1] < 0:
return False
return True
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
我们首先定义2booleanvariables设置为True-ascending和descending。然后遍历lst(我给了function一个更合理的param名称)并检查if这个index小于下一个。如果是,我们可以将ascendingvariable设置为False(因为lst现在不再是ascending). Else, if the next index is greater than the current索引, we set降序toFalse`。
直观地说,在这段代码中所做的工作如下:
如果一个序列是按升序排列的,那么每一个连续的数字对之间的差值将大于零,例如:考虑这个序列[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,则不按升序排序。
对于降序,请检查当前项与下一次之间的减法是否小于0,如果小于0,则不按降序排序。
试试这个:
如果
list
是ascending
或descending
,则返回True
。这使得
code
真正*可读**:我们首先定义
2
boolean
variables
设置为True
-ascending
和descending
。然后遍历lst
(我给了function
一个更合理的param
名称)并检查if
这个index
小于下一个。如果是,我们可以将ascending
variable
设置为False
(因为lst
现在不再是ascending). Else, if the next index is greater than the current
索引, we set
降序to
False`。最后,如果
lst
是ascending
or
descending
,我们就return
。一些例子:
希望这有帮助!(顺便说一下,如果你感兴趣,你可以在
one-line
中做同样的事情):这可能有助于:
执行时,此代码的输出为:
这里我们要做的是维护两个布尔标志
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
循环时使用上述代码的较小版本,请使用:以及输出
相关问题 更多 >
编程相关推荐