Computer Science, asked by rohangupta738, 8 months ago

In a list of integers l, the neighbours of l[i] are l[i-1] and l[i+1]. l[i] is a hill if it is strictly greater than its neighbours and a valley if it is strictly less than its neighbours.
Write a function counthv(l) that takes as input a list of integers l and returns a list [hc,vc] where hc is the number of hills in l and vc is the number of valleys in l.
Here are some examples to show how your function should work.


>>> counthv([1,2,1,2,3,2,1])
[2, 1]

>>> counthv([1,2,3,1])
[1, 0]

>>> counthv([3,1,2,3])
[0, 1]

Answers

Answered by iamvishnuvijay1999
17

Answer:

def counthv(l):

   count = [0, 0]

   for i in range(1, len(l)-1):

       if l[i - 1] > l[i] < l[i + 1]:

           count[1] += 1

       elif l[i - 1] < l[i] > l[i + 1]:

           count[0] += 1

   return count

Explanation:

Create a list  named as count and store 2 zeroes in it,

then take a for loop to traverse through the list and it should be ranging from 1 to len(list)-1 because we are taking l[i-1],l[i] and l[i+1] into consideration

and based on the above conditons we are gonna elevate the values of count and then finally we wil return the count

Similar questions