Python | Increment 1’s in list based on pattern

Given a list of binary numbers 0 and 1, Write a Python program to transform the list in such a way that whenever 1 appears after the occurrence of a sequence of 0’s, increment it by n+1, where ‘n’ is the last increment.

Examples:

Input : [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]
Output : [0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]

Input : [1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1]
Output : [1, 0, 2, 0, 0, 0, 3, 3, 0, 0, 4, 4, 4, 0, 5, 0, 6]

 
Approach #1 : Naive Approach

This is a naive approach to the given problem. It uses two variable ‘previous’ and ‘grp’ to store previously incremented number and to store the number of 1’s in a group. Now, using a for loop, increment 1’s accordingly.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to increment 1's in 
# list based on pattern 
  
def transform(lst):
      
    previous = 0
    grp = 0
    for elem in lst:
        if elem and not previous:
             grp += 1
        previous = elem
        yield (grp if elem else 0)
      
# Driver code
lst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]
x = (transform(lst))
res = []
for i in range(0, len(lst)):
    res.append(next(x))
print(res)

chevron_right


Output:

[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]

 

Approach #2 : Using count, chain and groupby from itertools module.
This is an efficient and more pythonic approach towards the given problem where we use count, chain and groupby from itertools module.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to increment 1's in 
# list based on pattern 
from itertools import * 
  
def transform(lst):
      
    c = count(1)
    return list(chain(*[list(g) if k != 1 else [next(c)]*len(list(g)) 
    for k, g in groupby(lst)]))
      
# Driver code
lst = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]
print(transform(lst))

chevron_right


Output:

[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ManasChhabra2



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.