
- 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 check all 1s are present one after another or not in Python
Suppose we have a list of numbers called nums that contains at least one element whose value is 1. We have to check whether all the 1s appear consecutively or not.
So, if the input is like nums = [8, 2, 1, 1, 1, 3, 5], then the output will be True.
To solve this, we will follow these steps −
visited := 0
for each x in nums, do
if x is same as 1, then
if visited is same as 2, then
return False
visited := 1
otherwise when visited is non-zero, then
visited := 2
return True
Example
Let us see the following implementation to get better understanding
def solve(nums): visited = 0 for x in nums: if x == 1: if visited == 2: return False visited = 1 elif visited: visited = 2 return True nums = [8, 2, 1, 1, 1, 3, 5] print(solve(nums))
Input
[8, 2, 1, 1, 1, 3, 5]
Output
True
- Related Articles
- Program to check three consecutive odds are present or not in Python
- Program to check whether one value is present in BST or not in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- Program to check whether one point can be converted to another or not in Python
- Program to check all listed delivery operations are valid or not in Python
- Program to check all values in the tree are same or not in Python
- Program to check whether all leaves are at same level or not in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- Program to find longest subarray of 1s after deleting one element using Python
- Program to check whether parentheses are balanced or not in Python
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check whether all can get a seat or not in Python
- Program to find longest number of 1s after swapping one pair of bits in Python
- How to check in R whether a matrix element is present in another matrix or not?

Advertisements