-2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    You do not need two for loops. `for i+1 in range(a)` does not make sense; you cannot assign a value to `i+1`, and you have no reason to: it's one higher than `i`. – khelwood Jan 26 '22 at 23:21
  • 2
    Welcome to StackOverflow! This is overall a pretty solid question: it's good that you've included sample output, and that you've shown your attempt! Good job. However, lines like: `for i in range(a) ` is missing the terminating `:`, your indentation is incorrect, and `for i+1 in range(a) ` does not make sense. I would recommend reviewing how `for` loops work in any form of Python tutorial. – Kraigolas Jan 26 '22 at 23:22
  • 2
    You condition writes its own code: `all(a[i]<=a[i+1] for i in range(0,len(a)-1))` – dawg Jan 27 '22 at 01:22

3 Answers3

1

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])))
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50
1

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
Lukasz Wiecek
  • 414
  • 2
  • 8
  • Worth noting that `sorted` is highly optimized for partially sorted lists, and will detect a fully sorted list in O(n) time without actually trying to do any "additional" sorting. – chepner Jan 27 '22 at 13:30
  • (Strictly speaking, that's probably an implementation detail of CPython, but the sorting algorithm used--TimSort--is also used in other languages, so I would be surprised if another Python implementation didn't use it as well.) – chepner Jan 27 '22 at 13:31
  • Yes, that's true, I am aware of TimSort :) Please note it will still have O(n log(n)) performance if the list has high entropy. Hence the complexity is O(n log(n)). BTW, I like the solution mentioned in the comment under the question that utilizes `all` instead of plain for like my second approach. – Lukasz Wiecek Jan 27 '22 at 19:49
0

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:])):
Alain T.
  • 40,517
  • 4
  • 31
  • 51