Home > Software design >  Identify Isotonic list or not
Identify Isotonic list or not

Time:02-08

I am working on identifying if the list is Isotonic or not.

I have this:

true_list = [5,4,3,1,1]
true_list1=list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if all(item[x]<=item[x 1]  for x in range(0,len(item)-1) or 
           item[x]>=item[x 1] for x in range(0,len(item)-1) ):
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))

I don't understand why for true_list it returns False

For f_list and f_list1 : It should be False and it is False.

Please advise.

Thank You

CodePudding user response:

This is happening because your if condition is incorrect. The all would return True if all conditions in it are True.

What you need is "(all numbers are decreasing monotonically) OR (all numbers are increasing monotonically)"

true_list = [5,4,3,1,1]
true_list1=true_list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if (all(item[x]<=item[x 1]  for x in range(0,len(item)-1)) or 
           all(item[x]>=item[x 1] for x in range(0,len(item)-1))) :
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))

outputs -

[5, 4, 3, 1, 1]
True
[1, 1, 3, 4, 5]
True
[5, 4, 9, 1, 1]
False
[1, 1, 9, 4, 5]
False
  •  Tags:  
  • Related