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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
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