0

How do I approach this? I've tried different ways and this is what I've so far . ex: [1, 2, 5, 7] returns True and [1, 1, 6, 9] returns False. The second example doesn't work. It returns true even though first two elements are equal. What am I doing wrong?

def increasing(L):
    n = len(L)
    i = 0
    while i <= n-1:
        if L[i] > L[i+1]:
            return False
        else:
            i+=1
    return True
Calcox
  • 1
  • 2

3 Answers3

4

Problem lies here

while i <= n:
    if L[i] > L[i+1]:

In your example, n=4. Since array index starts at 0, list index would be 0 1 2 3. You are checking till n=4 which is incorrect.

Then, you are doing [i+1] which checks for 5th element.

Replace with these lines

while i < n-1:
    if L[i] > L[i+1]:

This will take care of your index out of range error

Do I HAVE TO also use a for loop here?

No. Check Python - How to check list monotonicity

Community
  • 1
  • 1
sam
  • 2,033
  • 2
  • 10
  • 13
  • i wasnt the downvoter but i assume it has something to do with you saying Yes to having to use for loops. As lambo477 posted, and that would not be the only way to do it, there are definitely ways to do it without for loops. you were right however in stating the inherent problem of OP's post :) – R Nar Oct 30 '15 at 22:43
  • @RNar What I meant was in context with the OP's question. I misunderstood about basic functionalities which is why I removed that line so as to not create any confusion – sam Oct 30 '15 at 22:44
  • Thanks. It did solve the index out of range issue. However testing the code for [1, 1, 2, 3] would return True. It should be false as the first two elements are equal to each other. I feel like the function isn't iterating properly. maybe an indentation problem? Any help is appreciated! – Calcox Oct 30 '15 at 23:07
  • @Calcox Yeah. Change the condition to `L[i] >= L[i+1]` – sam Oct 30 '15 at 23:52
  • I was indeed being a stickler for the for loop part of the question. Now changed to an up vote! – gtlambert Oct 31 '15 at 11:29
1

This fixes your code. Your bound was actually 2 too high. I also removed some redundancy.

def increasing(L):
    i = 0
    while i < len(L) - 1:
        if L[i] > L[i+1]:
            return False
        i+=1
    return True
wvdz
  • 16,251
  • 4
  • 53
  • 90
0

Replace

while i <= n:

to

while i <= n-1:

Modified code :

def increasing(L):
    n = len(L)
    i = 0
    while i < n-1:
        if L[i] >= L[i+1]: #Equal to is also included as we want increasing sequence
            return False
        else:
            i+=1
    return True
R Nar
  • 5,465
  • 1
  • 16
  • 32
Pulkit Aggarwal
  • 79
  • 1
  • 10