Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
