Computer Science, asked by balavelan, 5 months ago

Write a function contracting(l) that takes as input a list of integer l and returns True if the absolute difference between each adjacent pair of elements strictly decreases.

Answers

Answered by ravilaccs
0

Answer:

Program is constructed for the given problem a function contracting(l) that takes as input a list of integer l and returns True if the absolute difference between each adjacent pair of elements strictly decreases.

Explanation:

>>> expanding([1,3,7,2,9])

 True

Explanation: Differences between adjacent elements are 3-1 = 2, 7-3 = 4, 7-2 = 5, 9-2 = 7.

 >>> expanding([1,3,7,2,-3])

 False

Explanation: Differences between adjacent elements are 3-1 = 2, 7-3 = 4, 7-2 = 5, 2-(-3) = 5, so not strictly increasing.

 >>> expanding([1,3,7,10])

 False

Program:

def expanding(l):

       diff= l[1]-l[0]

       for i in range(2,len(l)):

           if abs(l[i]-l[i-1])>diff:

               diff=abs(l[i]-l[i-1])

           else:

               return False

       return True    

Method 2:

Here are some examples of how your function should work.

 >>> accordian([1,5,1])

 False

Explanation: Differences between adjacent elements are 5-1 = 4, 5-1 = 4, which are equal.

>>> accordian([1,5,2,8,3])

 True

Explanation: Differences between adjacent elements are 5-1 = 4, 5-2 = 3, 8-2 = 6, 8-3 = 5, so the differences decrease, increase and then decrease.

>>> accordian([-2,1,5,2,8,3])

 True

Explanation: Differences between adjacent elements are 1-(-2) = 3, 5-1 = 4, 5-2 = 3, 8-2 = 6, 8-3 = 5, so the differences increase, decrease, increase and then decrease.

 >>> accordian([1,5,2,8,1])

 False

Explanation: Differences between adjacent elements are 1-(-2) = 3, 5-1 = 4, 5-2 = 3, 8-2 = 6, 8-1 = 7, so the differences increase, decrease, increase and then increase again.

Program

def contracting(l):

       try:

           diff= abs(l[1]-l[0])

           if abs(l[2]-l[1])>diff:

               flag = True

           else:

               flag = False

       except IndexError:

           return True    

       for i in range(2,len(l)):

           if flag and  abs(l[i]-l[i-1])>diff:

                     diff=abs(l[i]-l[i-1])

                     flag = not flag

           elif not flag and abs(l[i]-l[i-1])<diff:            

                     diff=abs(l[i]-l[i-1])

                     flag= not flag                      

           else:    

                     return False

                   return True      

Reference Link

  • https://brainly.in/question/12250690

   

Similar questions