python - Count all sequences in a list -


my self-learning task find how many sequences on list. sequence group of numbers, each 1 one bigger previous one. so, in list: [1,2,3,5,8,10,12,13,14,15,17,19,21,23,24,25,26] there 3 sequences: 1,2,3; 12,13,14,15; 23,24,25,26.

i've spent few hours , got solution, think workaround rather real solution.

my solution have separate list adding sequences , count attempts update list. count first appending, , every new appending except sequence, exists.

i believe there solution without additional list, allows count sequences rather list manipulation attempts.

numbers = [1,2,3,5,8,10,12,13,14,15,17,19,21,23,24,25,26]  goods = [] count = 0  in range(len(numbers)-1):     if numbers[i] + 1 == numbers[i+1]:          if goods == []:             goods.append(numbers[i])             count = count + 1          elif numbers[i] != goods[-1]:             goods.append(numbers[i])             count = count + 1          if numbers[i+1] != goods[-1]:             goods.append(numbers[i+1]) 

the output debugging:

number 1 added to: [1] first count change: 1  number 12 added to: [1, 2, 3, 12] normal count change: 2  number 23 added to: [1, 2, 3, 12, 13, 14, 15, 23] normal count change: 3 

one way iterate on pairwise elements:

l = [1,2,3,5,8,10,12,13,14,15,17,19,21,23,24,25,26]  res = [[]] item1, item2 in zip(l, l[1:]):  # pairwise iteration     if item2 - item1 == 1:         # difference 1, if we're @ beginning of sequence add both         # result, otherwise second 1 (the first 1         # included because of previous iteration).         if not res[-1]:  # index -1 means "last element".             res[-1].extend((item1, item2))         else:             res[-1].append(item2)     elif res[-1]:          # difference isn't 1 add new empty list in case ended sequence.         res.append([])  # in case "l" doesn't end "sequence" 1 needs remove trailing empty list. if not res[-1]:     del res[-1]  >>> res [[1, 2, 3], [12, 13, 14, 15], [23, 24, 25, 26]]  >>> len(res)  # amount of these sequences 3 

a solution without zip requires small changes (the loop , the beginning of loop) compared approach above:

l = [1,2,3,5,8,10,12,13,14,15,17,19,21,23,24,25,26]  res = [[]] idx in range(1, len(l)):     item1 = l[idx-1]     item2 = l[idx]     if item2 - item1 == 1:         if not res[-1]:             res[-1].extend((item1, item2))         else:             res[-1].append(item2)     elif res[-1]:          res.append([]) if not res[-1]:     del res[-1] 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -