简体   繁体   中英

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.
Output: the Boolean value True if for every i in the list a , a[i] <= a[i+1] ,
otherwise 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, 2] should return true. [1, 3, 2] should return 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.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

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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