Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract consecutive even numbers from a list?

In a list, a minimum of 2 even numbers makes a sequence: for example, a list that is [3, 18, 6, 5, 3, 4, 32, 8, 12] has 2 sequences that are even – which are 18, 6 and 4, 32, 8, 12.

How do I extract the sequences without extracting every even number individually?

def saisie():
    test = False
    while not test:
        N = int(input("donner N: "))
        test = 3<=N<=20
    return N

def remplir(N):
    t=[int]*N
    for i in range(N):
        element = input("enter an element:")
        t.append(element)
    return t

def seq(N, t):
    s=""
    for i in t:
        if t[i] and t[i+=]%2==0:
            s=   

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To group items with shared criteria, you can use groupby:

from itertools import groupby

nums = [3, 18, 6, 5, 3, 4, 32, 8, 12]

for is_even, grouper in groupby(nums, key=lambda x: x % 2 == 0):
    if is_even:
        evens = list(grouper)  # grouper objects have no len. Must convert to list
        if len(evens) >= 2:  # only consider sequences of at least 2 even numbers
            print(*evens)

Will give:

18 6
4 32 8 12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading