  # Python | N consecutive odd or even numbers

Python Methods and Functions

Method # 1: Using ` sum () ` + list comprehension + ` zip () + any () `

This problem can be solved with a combination of the above functions. This method solves the problem in 2 steps. In the 1st step, we calculate all possible pairs of N using lists and the zip function, and in the second step, we use the sum and any function to check for N the dividend result, if we find any of them, we return a positive value.

` `

` # Python3 demo code # N consecutive odd or even numbers # using sum () + zip () + any () + comprehension list   # initializing list test_list = [ 1 , 5 , 6 , 4 , 8 ]   # print original list print ( "The original list:" + str (test_list))    # initialization N N = 3   # using sum () + zip () + any () + comprehension list # 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)) `

` ` Output:

` The original list: [1, 5, 6, 4, 8] Does list contain the desired consecution: True `

Method # 2: Using ` groupby () + any () `

All the logic behind the 1st step in the above method can be controlled with the groupby function in which we do the grouping, and any function can be used later to check the consistency.

 ` # Python3 demo code ` ` # N consecutive odd or even numbers ` ` # using groupby () + any () ` ` from ` ` itertools ` ` import ` ` groupby `   ` # initializing list ` ` test_list ` ` = ` ` [` ` 1 ` `, ` ` 5 ` `, ` ` 6 ` `, ` ` 4 ` `, ` ` 8 ` `] `   ` # print original list ` ` print ( "The original list:" + str (test_list)) ``    # initialization N N = 3   # using groupby () + any () # N consecutive odd or even numbers res = any ( len ( list (sub)) = = N for idx, sub   in groupby ([sub % 2 for sub in test_list]))   # print result print ( "Does list contain the desired consecution:" + str (res)) `

Output:

` The original list: [1, 5, 6, 4, 8] Does list contain the desired consecution: True `