
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Changing Directions in Python
Suppose we have a list of numbers called nums, we have to find the number of times that the list changes from positive-to-negative or negative-to-positive slope.
So, if the input is like [2, 4, 10, 18, 6, 11, 13], then the output will be 2, as it changes the direction at 10 (positive-to-negative), and then at 6 (negative-to-positive).
To solve this, we will follow these steps −
To solve this, we will follow these steps −
for i in range 1 to size of nums - 1, do
if nums[i-1] < nums[i] > nums[i+1] or nums[i-1] > nums[i] < nums[i+1], then
count := count + 1
return count
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): count = 0 for i in range(1, len(nums) - 1): if nums[i - 1] < nums[i] > nums[i + 1] or nums[i - 1] > nums[i] < nums[i + 1]: count += 1 return count ob = Solution() print(ob.solve([2, 4, 10, 18, 6, 11, 13]))
Input
[2, 4, 10, 18, 6, 11, 13]
Output
2
- Related Articles
- Changing Class Members in Python?
- Changing ttk Button Height in Python
- Program to traverse binary tree using list of directions in Python
- Why did changing list ‘y’ also change list ‘x’ in Python?
- Changing program title in SAP
- Changing color randomly in JavaScript
- Changing year in MySQL date?
- What are the cardinal directions?
- Changing the Mouse Cursor in Tkinter
- Changing the Replication Factor in Cassandra
- In how many directions can a Ray extends?
- Methodological Issues in Aging Research and Future Directions
- Changing Attitudes through Persuasion
- Changing Others' Behavior
- Program to find largest island after changing one water cell to land cell in Python

Advertisements