0

So I've been at this for a while. I'm trying to create a function that checks if the numbers in a list are increasing. For example [1, 2, 3] is True but [1, 3, 2] is False. I have gotten to the point where it will say [1, 2, 3] is True, [3, 2, 1] is False, but [1, 3, 2] is still True. I assume it is only because only the first two positions are being read?

Here is the function for reference:

 def increasing(lst):
    index = 0
    index2 = index + 1
    while index < len(lst):
        if lst[index] >= lst[index2]:
            index += 1
            index2 += 1
            return False
        else:
            while index < len(lst):
                if lst[index] < lst[index2]:
                    index += 1
                    index2 += 1
                    return True
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94

2 Answers2

2

Try this:

def increasing(lst):
    return lst == sorted(lst)

This checks whether the list is sorted.

Johannes Overmann
  • 4,914
  • 22
  • 38
  • 1
    This is slower than running through the list linearly ( O(n log(n)) vs O(n) ), but is probably fine for most situations. – BallpointBen Oct 30 '15 at 23:37
1

Your code seems overly complicated. Just check with a loop that i-th element is larger than (i-1)-th element and you're done.

EDIT: here's the simple code

def isSorted(l):
    i = 1
    while i < len(l):
        if l[i] < l[i-1]:
            return False
        i += 1
    return True
isSorted([1, 2, 3]) #True
isSorted([1, 3, 2]) #False
AkiRoss
  • 11,745
  • 6
  • 59
  • 86
  • Duh, naturally, there's always someone downvoting without caring to say why :( – AkiRoss Oct 30 '15 at 23:17
  • 1
    hey thanks for the response, this helped a lot! – liam tapp Oct 30 '15 at 23:22
  • 1
    While `lst == sorted(lst)` in the other answer is technically correct, if the input list is not sorted, it sorts it and creates a new sorted list. That is all work that is wasted in this case. Whereas, this approach short-circuits once it detects a single value out of order. So although seemingly not as Pythonic, I would think this solution here is higher performing for large lists. – RobertB Oct 30 '15 at 23:31