- 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

# Program to find length of longest sign alternating subsequence from a list of numbers in Python

Suppose we have a list of numbers called nums, we have to find the length of longest subsequence that flips sign on each consecutive number.

So, if the input is like nums = [1, 3, -6, 4, -3], then the output will be 4, as we can pick [1, -6, 4, -3].

To solve this, we will follow these steps −

- pos := 0, neg := 0
- for each n in nums, do
- if n < 0, then
- neg := pos + 1

- otherwise,
- pos := neg + 1

- if n < 0, then
- return maximum of pos and neg

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums): pos = neg = 0 for n in nums: if n < 0: neg = pos + 1 else: pos = neg + 1 return max(pos, neg) ob = Solution() nums = [1, 3, -6, 4, -3] print(ob.solve(nums))

## Input

[1, 3, -6, 4, -3]

## Output

4

- Related Articles
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest interval from a list of intervals in Python
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence in C++

Advertisements