Sunday, February 25, 2018

Python program : To check if given list of integers is a valley

A list of integers is said to be a valley if it consists of a sequence of strictly decreasing values followed by a sequence of strictly increasing values. The decreasing and increasing sequences must be of length at least 2. The last value of the decreasing sequence is the first value of the increasing sequence.

Write a Python function valley(l) that takes a list of integers and returns True if l is a valley and False otherwise.

Here are some examples to show how your function should work.


>>> valley([3,2,1,2,3])
True
>>> valley([3,2,1])
False
>>> valley([3,3,2,1,2])
False 
 
def valley(l): 
  n=len(l)
  downhill=0
  uphill=0
 
  
  for i in range(0,n-1):
      
    if(l[i]>l[i+1]):
       downhill +=1
    else:
      if i==(n-1):
        break
      elif(l[i]<l[i+1]):
        uphill +=1
      else:
          return(False)
  return(True)
 
 
Thanks
Happy Programming ! 
 

No comments:

Post a Comment

Sacred Thought

5 May 2024 Hari Om Verse 50-51, chapter two:  In this chapter two Shree krishna explains a simple way of living. Free from desires and void ...