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

To count how many consecutive pairs in a list of numbers

To count how many consecutive pairs of number in a list, here’s an example:

[150,151,152,262]

There are 2 consecutive pairs, which are 150 & 151, 151 & 152.

I try below:

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

import more_itertools as mit
import itertools

iterable = [150,151,152,262]

tem_list = [list(group) for group in mit.consecutive_groups(iterable)]
# [[150, 151, 152], [262]]

i = 0
for t in tem_list:
    if len(t) == 1:
        i = 0
    if len(t) == 2:
        i += 1
    if len(t) == 3:
        i += 2      
print (i)

But it doesn’t work. What went wrong, and how can I correct it?

>Solution :

Using a grouping function for this is overkill. You can use zip() to pair each item with its successor and add the result of comparing them using the sum function:

L = [150,151,152,262]
C = sum(a+1==b for a,b in zip(L,L[1:]))
print(C) # 2
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