[英]How do I check if every consecutive list element is equal to or 1 more than the last?
Input: a list a of real numbers, of length 0 or greater.输入:长度为 0 或更大的实数列表 a。
Output: the Boolean valueTrue
if for everyi
in the lista
,a[i] <= a[i+1]
, Output:Boolean 值 如果对于列表a
中的每个i
,a[i] <= a[i+1]
,则为True
,
otherwiseFalse
.否则False
。
This is what I have so far but it doesn't work:这是我到目前为止所拥有的,但它不起作用:
def consecutive_elements_equal_or_one_more(a):
for i in range(a)
for i+1 in range(a)
if a[i] <= a[i+1]:
return true
else:
return false
[1, 2, 3]
should return true. [1, 2, 3]
应该返回 true。 [1, 2, 2]
should return true. [1, 2, 2]
应该返回 true。 [1, 3, 2]
should return false. [1, 3, 2]
应该返回 false。
If you're looking for an efficient way of doing this and the lists are numerical, you would probably want to use numpy and apply the diff (difference) function:如果您正在寻找一种有效的方法并且列表是数字的,您可能希望使用 numpy 并应用差异(差异)function:
>>> numpy.diff([1,2,3,4,5,5,6])
array([1, 1, 1, 1, 0, 1])
Then to get a single result regarding whether there are any consecutive elements:然后得到一个关于是否有任何连续元素的结果:
>>> numpy.any(~numpy.diff([1,2,3,4,5,5,6]).astype(bool))
This first performs the diff, inverts the answer, and then checks if any of the resulting elements are non-zero.这首先执行差异,反转答案,然后检查任何结果元素是否非零。
Similarly,相似地,
>>> 0 in numpy.diff([1, 2, 3, 4, 5, 5, 6])
also works well and is similar in speed to the np.any approach也很有效,速度与 np.any 方法相似
Solution without third party libraries:没有第三方库的解决方案:
ls = [
[1, 2, 3],
[1, 2, 2],
[1, 3, 2]
]
for l in ls:
print(all(a - b <= 1 for a, b in zip(l, [l[0] - 1, *l])))
Based on these conditions you need to check if the list is already sorted.根据这些条件,您需要检查列表是否已排序。
Simple solution:简单的解决方案:
def is_sorted(a):
return a == sorted(a)
Faster, without sorting the list first:更快,无需先对列表进行排序:
def is_sorted(a):
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
return False
return True
Your question title and problem statement are inconsistent.您的问题标题和问题陈述不一致。
Checking for non decreasing order can be done with all
and zip
:可以使用all
和zip
检查非递减顺序:
if all(a<=b for a,b in zip(a,a[1:])):
Checking for "one or more than the last":检查“一个或多个”:
if all(a+1<=b for a,b in zip(a,a[1:])):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.