Home > Software design >  Python fetch all consecutive odd or even numbers
Python fetch all consecutive odd or even numbers

Time:06-23

Given a list of integers, how can I group together consecutive numbers that share the same parity?

Here is an example input:

[5, 9, 11, 20, 24, 30, 31, 33, 39, 41]

And here is an example output:

[[5, 9, 11], [20, 24, 30], [31, 33, 39, 41]]

CodePudding user response:

a simple loop does the job:

test = [5,7,9,11,13,20,22,24,31,33,39,41,43,44,46,50,52]

result = []
res = []
prevalue = None
for v in test:
    if prevalue == None or v == prevalue   2:
        prevalue = v
        res.append(v)
    else:
        prevalue = v
        result = [res]
        res = [v]

result = [res]

print(result)

result:

[[5, 7, 9, 11, 13], [20, 22, 24], [31, 33], [39, 41, 43], [44, 46], [50, 52]]

CodePudding user response:

You can use itertools.groupby() to produce the groupings of odd / even numbers:

[list(group) for _, group in groupby(data, lambda x: x % 2 == 0)]

This outputs:

[[5, 9, 11], [20, 24, 30], [31, 33, 39, 41]]

CodePudding user response:

Basically, what you want to do is track the current list you're looking at and modify it as you go and, when your condition no longer holds true, you save the list and create a new one:

results = []
current = [data[0]]
flag = data[0] % 2
for number in data[1:]:
    if number % 2 == flag:
        current.append(number)
    else:
        flag = 1 - flag
        results.append(current)
        current = [number]
results.append(current)
  • Related