Here is the function:
def is_sorted(L):
""" (str) -> Bool
Return True iff the L is sorted in nondecreasing order. Otherwise, return
False.
>>> is_sorted([1, 2, 3, 3])
True
>>> is_sorted([3, 2, 1, 3])
False
"""
if len(L) == 0:
return False
for i in range(len(L) - 1):
if L[i] > L[i + 1]:
return False
return True
Then I executed it on a list with one character and it returns True. However, I expected to receive 'list index out of range error'. Could anyone explain why does it behave in such way?
range(a, b, s) is [a, a+s, a+2*s..., x] where x < b.
So range(0) -> range(0,0,1) generates an empty list. This means the inside of the for loop is skipped which returns True.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With