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
-
Economics & Finance
Program to check three consecutive odds are present or not in Python
Suppose we have an array called nums, we have to check whether there are three consecutive odd numbers in nums or not.
So, if the input is like nums = [18,15,2,19,3,11,17,25,20], then the output will be True as there are three consecutive odds [3,11,17].
Algorithm
To solve this, we will follow these steps −
Get the length of nums
If length is 1 or 2, return False (impossible to have 3 consecutive elements)
Otherwise, iterate through the array checking each group of 3 consecutive elements
If all three elements in any group are odd, return True
If no group of 3 consecutive odds is found, return False
Method 1: Using Modulo Operator
Check if each number is odd using the modulo operator ?
def solve(nums):
length = len(nums)
if length == 1 or length == 2:
return False
else:
for i in range(len(nums) - 2):
if nums[i] % 2 != 0 and nums[i+1] % 2 != 0 and nums[i+2] % 2 != 0:
return True
return False
nums = [18, 15, 2, 19, 3, 11, 17, 25, 20]
print(solve(nums))
True
Method 2: Using Bitwise AND
An alternative approach using bitwise AND operation to check if numbers are odd ?
def check_three_consecutive_odds(nums):
if len(nums) < 3:
return False
for i in range(len(nums) - 2):
if (nums[i] & 1) and (nums[i+1] & 1) and (nums[i+2] & 1):
return True
return False
# Test with different examples
test_cases = [
[18, 15, 2, 19, 3, 11, 17, 25, 20], # True
[2, 4, 6, 8], # False (all even)
[1, 3, 5], # True (all odd)
[1, 2, 3, 4, 5], # False (no 3 consecutive odds)
[1, 2] # False (less than 3 elements)
]
for i, nums in enumerate(test_cases):
result = check_three_consecutive_odds(nums)
print(f"Test {i+1}: {nums} ? {result}")
Test 1: [18, 15, 2, 19, 3, 11, 17, 25, 20] ? True Test 2: [2, 4, 6, 8] ? False Test 3: [1, 3, 5] ? True Test 4: [1, 2, 3, 4, 5] ? False Test 5: [1, 2] ? False
Comparison
| Method | Operation | Time Complexity | Readability |
|---|---|---|---|
| Modulo (%) | num % 2 != 0 |
O(n) | High |
| Bitwise AND | num & 1 |
O(n) | Medium |
Key Points
Arrays with fewer than 3 elements cannot have 3 consecutive odds
We only need to check up to
len(nums) - 2to avoid index errorsBoth modulo and bitwise methods work equally well for checking odd numbers
The function returns
Trueas soon as the first group of 3 consecutive odds is found
Conclusion
Use the modulo operator method for better readability. The bitwise AND approach offers a slight performance advantage but is less intuitive. Both methods efficiently solve the problem in O(n) time complexity.
