Home > Back-end >  I am finding monotone but it is saying bool object is not iterable
I am finding monotone but it is saying bool object is not iterable

Time:03-20

def ismonotone(a):
    n = len(a)
    for i in range(0, n-1) 
        if all(a[i] >= a[i 1] or a[i] <= a[i 1]):
            return True
        else:
            return False

A = [6, 5, 4, 2]
print(ismonotone(A))

CodePudding user response:

The result of comparison operator is either True or False. So inside your all() you have something like True/False or True/False which ends up to either True or False. That's why you get that error. all() accepts an iterable.

Also, for Monotonic you need to check both increasing and decreasing.

def ismonotone(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)))

A = [6, 5, 4, 2]
print(ismonotone(A))  # True

CodePudding user response:

if all(a[i]>=a[i 1]or a[i]<=a[i 1] ):

You're using all() incorrectly. You're supposed to pass it a sequence of values, and it returns true if all of those values are true; otherwise it returns false. You didn't pass a sequence of values.

But beyond that, it's not even clear what you wanted. You're using all(), but then inside it you have an or condition. So are you trying to check if BOTH of the conditions are true, or if EITHER is true?

In either case, a simple and/or expression is the right way to check. So why are you using all() anyway?

  • Related