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.
# 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) |
[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.
# 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)) |
[0, 1, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3]
Recommended Posts:
- Python | Filter list of strings based on the substring list
- Python | Add list elements with a multi-list based on index
- Python | Filter a list based on the given list of strings
- Python | Group list elements based on frequency
- Python | Split list of strings into sublists based on length
- Python | Filter dictionary key based on the values in selective list
- Python | Increasing alternate element pattern in list
- Python | Increment value in dictionary
- Ways to increment a character in Python
- Increment and Decrement Operators in Python
- Image based Steganography using Python
- Thread-based parallelism in Python
- Movie recommendation based on emotion in Python
- Python | Sort tuple based on occurrence of first element
- Filtering Images based on size attributes in Python
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



