Python | N consecutive Odd or Even Numbers
Last Updated :
15 May, 2023
The problem focused on in this article is quite specific and may be less useful in different domains. But the way this is going to solve may open doors to solve potentially like problems, hence making it worth a read. This article solves the problem of testing if a list contains a series of odd or even elements. Let's discuss certain ways in which this problem can be solved.
Method #1: Using sum() + list comprehension + zip() + any()
This problem can be solved using a combination of the above functions. This method solves the problem in 2 steps. In 1st step, we compute all the possible pairs of N using list comprehension and zip function and in the second step we use sum and any function to test for N divisible result, if we find any one of them, we return positive.
Python3
# Python3 code to demonstrate
# N consecutive Odd or Even Numbers
# using sum() + zip() + any() + list comprehension
# initializing list
test_list = [1, 5, 6, 4, 8]
# printing original list
print("The original list : " + str(test_list))
# initializing N
N = 3
# using sum() + zip() + any() + list comprehension
# N consecutive Odd or Even Numbers
temp = (test_list[i: i + N] for i in range(len(test_list) - N + 1))
res = any(sum(ele % 2 for ele in temps) % N == 0 for temps in temp)
# print result
print("Does list contain the desired consecution : " + str(res))
OutputThe original list : [1, 5, 6, 4, 8]
Does list contain the desired consecution : True
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The sum() + list comprehension + zip() + any() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(1) constant additional space is required.
Method #2: Using groupby() + any()
The whole logic of doing the 1st step in the above method can be managed using the groupby function in which we perform the grouping and any function can be used later for checking the consecution.
Python3
# Python3 code to demonstrate
# N consecutive Odd or Even Numbers
# using groupby() + any()
from itertools import groupby
# Initializing list
test_list = [1, 5, 6, 4, 8]
# Printing original list
print("The original list : " + str(test_list))
# Initializing value
N = 3
# N consecutive Odd or Even Numbers
# using groupby() + any()
res = any(len(list(sub)) == N for idx, sub in
groupby([sub % 2 for sub in test_list]))
# Printing result
print("Does list contain the desired consecution : " + str(res))
OutputThe original list : [1, 5, 6, 4, 8]
Does list contain the desired consecution : True
Time complexity: O(N), where N is the length of the input list test_list.
Auxiliary space: O(N), as the groupby() function creates an iterator that produces a new group object for each unique consecutive sequence of parity in the input list.
Method #3: Using all()
The code first initializes test_list and N. Then it iterates over sublists of test_list with length N, using a generator expression. For each sublist, it checks if all elements have the same parity (odd or even) by comparing the parity of the first element to the parity of the other elements. If the condition is met, it sets the result to True and exits the loop. If the loop ends without finding a sublist that meets the condition, it sets the result to False. Finally, it prints the result.
Python3
# Initialize test_list and N
test_list = [1, 5, 6, 4, 8]
N = 3
# Printing original list
print("The original list : " + str(test_list))
# Iterating over sublists of test_list with length N
for group in (test_list[i:i+N] for i in range(len(test_list)-N+1)):
# Checking if all elements in the sublist have the same parity (odd or even)
if all(num % 2 == group[0] % 2 for num in group):
# If the condition is met, set result to True and exit the loop
result = True
break
# If the loop ends without finding a sublist that meets the condition,
# set result to False
else:
result = False
# Printing result
print("Does list contain the desired consecution : " + str(result))
# This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list : [1, 5, 6, 4, 8]
Does list contain the desired consecution : True
Time complexity: O(n), since it iterates over the elements of test_list once.
Auxiliary space: O(1), since the size of the variables used is constant and independent of the size of the input.
Method #4: Using numpy array slicing and broadcasting
The numpy approach for solving this problem involves converting the input list to a numpy array, slicing the array to create subarrays of length N, and then checking if all the elements in each subarray have the same parity (odd or even) using numpy broadcasting.
Python
import numpy as np
# Initializing test_list and value
test_list = [1, 5, 6, 4, 8]
N = 3
# Converting test_list to numpy array
arr = np.array(test_list)
# Slicing the array to create subarrays of length N
subarrays = arr[np.arange(len(arr)-N+1)[:, None] + np.arange(N)]
# Check if all the elements in each subarray have
# same parity (odd or even) using numpy broadcasting
result = np.all(subarrays % 2 == subarrays[0] % 2, axis=1).any()
# Print the result
print("Does list contain the desired consecution : " + str(result))
Output:
Does list contain the desired consecution : True
Time complexity: O(n), since it involves slicing the numpy array, which takes constant time.
Auxiliary space: O(n), since it creates a numpy array of size n and subarrays of size N.
Similar Reads
Python program to count Even and Odd numbers in a Dictionary Given a python dictionary, the task is to count even and odd numbers present in the dictionary. Examples: Input : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e' : 5}Output : Even = 2, odd = 3Input : {'x': 4, 'y':9, 'z':16}Output : Even = 2, odd = 1 Approach using values() Function: Traverse the dictionary and
3 min read
Python Program to Check if a Number is Odd or Even Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1.In this article, we will learn how to check if
2 min read
Python Program for Frequencies of even and odd numbers in a matrix Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix Examples: Input : m = 3, n = 3 { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } Output : Frequency of odd number = 5 Frequency of even number = 4 Input : m = 3, n = 3 { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 1
4 min read
Python - Check if list contains consecutive Checking if a list contains consecutive numbers in Python is useful in problems involving sequences, patterns, or data validation. In this article, we explore different methods to check for consecutive numbers in a list.Using sorted() and RangeThis method works by sorting the list and comparing it t
2 min read
Python - Check if list contains consecutive Checking if a list contains consecutive numbers in Python is useful in problems involving sequences, patterns, or data validation. In this article, we explore different methods to check for consecutive numbers in a list.Using sorted() and RangeThis method works by sorting the list and comparing it t
2 min read
Python - Check if list contains consecutive Checking if a list contains consecutive numbers in Python is useful in problems involving sequences, patterns, or data validation. In this article, we explore different methods to check for consecutive numbers in a list.Using sorted() and RangeThis method works by sorting the list and comparing it t
2 min read