Reputation: 35
I was working on this Leetcode problem. I managed to solve it and later looked upon the solution to find this :-
class Solution(object):
## A is the Given Array
def isMonotonic(self, A):
return (all(A[i] <= A[i+1] for i in range(len(A) - 1)) or
all(A[i] >= A[i+1] for i in range(len(A) - 1)))
My doubt is regarding the usage of all() in this manner - all(A[i] <= A[i+1] for i in range(len(A) - 1))
, clearly all() is being called with a boolean parameter and it works. But when I executed all(True)
in python console I got TypeError: 'bool' object is not iterable
. So basically how did the usage of all() in this manner work in the code but not in the console.
My another doubt is in A[i] <= A[i+1] for i in range(len(A) - 1)
. When i
reaches the last index value of the list shouldn't A[i] <= A[i+1]
raise an IndexError: list index out of range
.
Upvotes: 1
Views: 50
Reputation: 628
This is an example of list comprehension.1 In this instance, the input to all()
is a list of booleans, which could be rewritten as a for
loop like so:
bools = []
for i in range(len(A) - 1):
bools.append(A[i] <= A[i + 1])
all(bools)
For your second doubt, we can look to the definition of the range()
function (emphasis mine):
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
Essentially, the range
method is exclusive on the maximum, meaning the generator range(len(A)-1)
will only go up to len(A) - 2
.
1: Technically this isn't a list but a generator. The difference is that a generator only creates new values as needed, rather than all of them at the same time. See this answer on the definition of yield
for a more in-depth look.
Upvotes: 2