Program to check whether list is alternating increase and decrease or not in Python


Suppose we have a list of numbers called nums. We have to check whether the list alternates starting from strictly increasing then strictly decreasing and then strictly increasing and so on. And also if the list is only strictly increasing, it will be valid.

So, if the input is like nums = [2, 4, 8, 7, 5, 1, 5, 7, 2, 1], then the output will be True, because [2,4,8] are increasing, then [7,5,1] is decreasing, then again [5,7] is increasing and [2,1] is decreasing.

To solve this, we will follow these steps −

  • if nums[1] <= nums[0], then
    • return False
  • for i in range 0 to size of nums, do
    • if i - 1 >= 0, then
      • if nums[i] is same as nums[i - 1], then
        • return False
  • return True

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   if nums[1] <= nums[0]:
      return False
   for i in range(len(nums)):
      if i - 1 >= 0:
         if nums[i] == nums[i - 1]:
            return False

   return True

nums = [2, 4, 8, 7, 5, 1, 5, 7, 2, 1]
print(solve(nums))

Input

[2, 4, 8, 7, 5, 1, 5, 7, 2, 1]

Output

True

Updated on: 14-Oct-2021

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements