The initialization of a list with a single number is a generic problem whose solution has been dealt with many times. But sometimes we require to initialize the list with elements alternatively repeating K no. of times. This has use cases in M.L. or A. I algorithms that require presetting of data in lists. Let’s discuss certain ways in which this problem is solved.
Method #1: Using list comprehension In this method, we insert elements in the list alternatively for the specific number of times of each element’s occurrence. It takes the remainder of the sum of counts of both occurrences of elements with the particular occurrence of elements for cycle computation.
Python3
# Python3 code to demonstrate # to perform cyclic initialization # using list comprehension # count of 1 count_1 = 4 # count of 0 count_0 = 3 # total length of list size = 14 # initializing list cyclically # using list comprehension test_list = [ 1 if i % (count_1 + count_0) < count_1 else 0 for i in range (size)] # printing list after change print ( "The list after initializing : " + str (test_list)) |
The list after initializing : [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
Time complexity: O(n), where n is the size of the list.
Auxiliary space: O(n), for the list test_list.
Method #2 : Using itertools.cycle() + itertools.islice() This is the most pythonic way in which we can perform the cyclic initialization. Slice each of the part of list into the allotted element size in a cyclic manner using cycle function.
Step-by-step approach:
- Import the itertools module, which contains various functions to work with iterators.
- Define the count of 1’s (count_1), count of 0’s (count_0), and the total length of the list (size) as integers.
- Create a list pattern by concatenating count_1 number of 1’s and count_0 number of 0’s. This is the pattern that will be repeated cyclically to initialize the list.
- Use the itertools.cycle() function to create an infinite iterator that will cycle through the pattern list repeatedly.
- Use the itertools.islice() function to create a new iterator that only returns the first size elements of the cyclic iterator.
- Convert the iterator returned by itertools.islice() to a list using the list() function. This list will be the initialized list.
- Print the initialized list using the print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate # to perform cyclic initialization # using itertools.cycle() + itertools.islice() import itertools # count of 1 count_1 = 4 # count of 0 count_0 = 3 # total length of list size = 16 # getting pattern pattern = [ 1 ] * count_1 + [ 0 ] * count_0 # initializing list cyclically # using itertools.cycle() + itertools.islice() test_list = list (itertools.islice(itertools.cycle(pattern), size)) # printing list after change print ( "The list after initializing : " + str (test_list)) |
The list after initializing : [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1]
Time complexity: O(n), where n is the size of the list.
Auxiliary space: O(n), where n is the size of the list.
Method #3 : Using *,extend() and slicing
Python3
# Python3 code to demonstrate # to perform cyclic initialization # using list comprehension # count of 1 count_1 = 4 # count of 0 count_0 = 3 # total length of list size = 14 # initializing list cyclically x = [ 1 ] * count_1 y = [ 0 ] * count_0 res = [] while ( len (res) < = size): res.extend(x) res.extend(y) res = res[:size] # printing list after change print ( "The list after initializing : " + str (res)) |
The list after initializing : [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
Time complexity: O(size), as the while loop iterates until the desired size of the list is achieved, and extending a list takes constant time.
Auxiliary space: O(size), as the final list occupies a space of size ‘size’ in memory.
Method #4 : Using itertools.repeat():
To use the repeat() function from the itertools module to initialize a list with alternate 0s and 1s, you can use the following approach:
Python3
from itertools import repeat # count of 1s count_1 = 4 # count of 0s count_0 = 3 # total length of list size = 14 # initialize list with alternate 0s and 1s test_list = list (repeat( 1 , count_1)) + list (repeat( 0 , count_0)) # repeat list until it has the desired size test_list = test_list * (size / / len (test_list)) + test_list[:size % len (test_list)] # print list after initialization print ( "The list after initializing:" , test_list) #This code is contributed by Edula Vinay Kumar Reddy |
The list after initializing: [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
Time complexity: O(n), where n is the size of the final list. This is because the time taken to create the list is directly proportional to the size of the list.
Auxiliary space: O(n), because the size of the final list is directly proportional to the size of the input.
Method #5: Using a while loop
Step-by-step approach:
- Initialize an empty list “test_list“
- Create a while loop that runs until the length of “test_list” is equal to “size“
- Inside the loop, add “count_1″ number of 1s to “test_list” using list concatenation and “count_0” number of 0s using list concatenation.
- If the length of “test_list” is greater than “size“, slice the list to get the first “size” elements.
- Print the final “test_list“.
Below is the implementation of the above approach:
Python3
# count of 1s count_1 = 4 # count of 0s count_0 = 3 # total length of list size = 14 # initialize list with alternate 0s and 1s test_list = [] # repeat list until it has the desired size while len (test_list) < size: test_list + = [ 1 ] * count_1 test_list + = [ 0 ] * count_0 if len (test_list) > size: test_list = test_list[:size] # print list after initialization print ( "The list after initializing:" , test_list) |
The list after initializing: [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
Time complexity: O(size)
Auxiliary space: O(size)
Method #6: Using numpy.tile():
Algorithm:
- Import the numpy library and alias it as np for convenience.
- We define count_1, count_0, and size variables as in the original code.
- We create two numpy arrays, ones, and zeros, with lengths count_1 and count_0 respectively.
- Concatenate the two arrays to form a cycle of length count_1 + count_0.
- Now, use numpy.tile() function to repeat the cycle enough times to fill a list of length size.
- Slice the resulting array to get the desired length and print the resulting list.
Below is the implementation of the above approach:
Python3
import numpy as np # count of 1 count_1 = 4 # count of 0 count_0 = 3 # total length of list size = 14 # initializing list cyclically using # numpy.tile() ones = np.ones(count_1) zeros = np.zeros(count_0) cycle = np.concatenate((ones, zeros)) test_list = np.tile(cycle, size / / len (cycle) + 1 )[:size] # printing list after change print ( "The list after initializing : " + str (test_list)) |
Output:
The list after initializing : [1. 1. 1. 1. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0.]
Time Complexity: O(size)
Auxiliary Space: O(size) (numpy arrays are created to form the cycle and the resulting list)