Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Identify Isotonic list or not

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Please advise.

Thank You

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading