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.

` ` |

** Output: **

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

It would be easy for me to develop native apps using Java, C++ or Objective-C and I am also able to learn Kotlin, Dart or Swift, but things are much easier when you just use Python. I have done a Djan...

23/09/2020

Become a master in Python by learning coding best practices and advanced programming concepts in Python 3.7. This book is written for Python developers who wish to go further in mastering Python. A...

23/09/2020

Executing Data Quality Projects: Ten Steps to Quality Data and Trusted Information (TM), 2nd Edition. Execute Data Quality Projects, Second Edition presents a structured yet flexible approach to cr...

28/08/2021

We live in an age of so-called Big Data. We hear terms like data scientist, and there is much talk about analytics and the mining of large amounts of corporate data for tidbits of business value. Ther...

10/07/2020

X
# Submit new EBook