- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if nums[i] is same as nums[i - 1], then
- if i - 1 >= 0, then
- 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
Advertisements