Python | Increasing alternate element pattern in list
Last Updated :
24 Apr, 2023
This particular article solves a very specific issue in which we need to insert every alternate element as the increased size pattern of repeated element to form a pattern. This can have a utility in demonstrative projects. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + enumerate() List comprehension with the help of enumerate function can be used to perform this particular task in which we use the tuple which increases its length every alternate element for the insertion using the enumerate function.
Python3
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The original list : " + str (test_list))
res = [j for sub in ((i, '*' * k)
for k, i in enumerate (test_list, 1 ))
for j in sub]
print ( "The increasing element pattern list : " + str (res))
|
Output
The original list : [1, 2, 3, 4, 5]
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using itertools.chain.from_iterable() + zip() This task can be performed efficiently using the above functions. The zip function interleaves the formed strings using string multiplication with the lists and from_iterable function does the task of flattening the obtained tuples.
Python3
import itertools
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The original list : " + str (test_list))
res = list (itertools.chain.from_iterable(
zip (test_list, ( "*" * (i + 1 )
for i in range ( len (test_list))))))
print ( "The increasing element pattern list : " + str (res))
|
Output
The original list : [1, 2, 3, 4, 5]
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using extend() and * operator
Python3
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The original list : " + str (test_list))
res = []
for i in range ( 0 , len (test_list)):
x = [test_list[i], "*" * test_list[i]]
res.extend(x)
print ( "The increasing element pattern list : " + str (res))
|
Output
The original list : [1, 2, 3, 4, 5]
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), because we are creating a new list res that has a length of 2n, where n is the length of the test_list.
Method #3 : Using repeat() and chain() from itertools
This code imports the chain() and repeat() functions from the itertools module. It then defines a function called increase_pattern() that takes in a list as an argument.
The function first uses the zip() function to pair the elements in the input list with their corresponding indices. It then uses a list comprehension to multiply each element by its corresponding index and create a list of tuples.
Next, the function uses the chain() function to flatten the list of tuples into a single list. It does this by passing the chain() function the result list as an argument, preceded by the * operator.
Python3
from itertools import chain, repeat
def increase_pattern(lst):
pairs = zip (lst, range ( 1 , len (lst) + 1 ))
result = [(elem, " ".join(repeat(" * ", index))) for elem, index in pairs]
result = list (chain( * result))
return result
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The increasing element pattern list : " + str (increase_pattern(test_list)))
|
Output
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time complexity: O(n), where n is the length of the input list. This is because the function iterates over the input list once to create the pairs, and again to create the result list.
Auxiliary space: O(n), as the size of the output list is directly proportional to the size of the input list.
Method 4: Using a for loop and append()
- Initialize an empty list res to store the output
- Loop over each element elem and its index i in the list test_list using the enumerate function
- Append the current element elem to the result list res
- Append a string of i+1 asterisks to the result list res
- Use string multiplication to create the required number of asterisks, i.e., ‘*’ * (i+1)
- Looping through all the elements and asterisks, we get the required increasing alternate element pattern list.
- Print the final list res using the print statement.
Below is the implementation:
Python3
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The original list : " + str (test_list))
res = []
for i, elem in enumerate (test_list):
res.append(elem)
res.append( '*' * (i + 1 ))
print ( "The increasing element pattern list : " + str (res))
|
Output
The original list : [1, 2, 3, 4, 5]
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time complexity: O(n), where n is the number of elements in the input list test_list. This is because we are iterating over each element in the list once and performing constant time operations.
Auxiliary space: O(n), since we are creating a list res of size 2n, where n is the number of elements in the input list test_list. This is because we are adding an asterisk string after each element in the list.
Method #6: Using map() and lambda function
In this method, we use the map() function along with a lambda function to iterate over the list and generate the resulting list. We use the lambda function to add stars to the list based on the index.
- Initialize a list named test_list with the values [1, 2, 3, 4, 5]
- Print the original list using the print() function
- Create a lambda function that takes an index i as input and returns a list containing the element at the ith index of test_list and a string of asterisks (*) of length (i+1).
- Use the map() function to apply the lambda function to each index in the test_list and create a list of lists.
- Convert the resulting list of lists into a flattened list using a list comprehension that iterates over each sublist and each element in each sublist.
- Print the resulting list using the print() function, with a message that describes the list as an “increasing element pattern list”.
- The resulting output should look like.
Python3
test_list = [ 1 , 2 , 3 , 4 , 5 ]
print ( "The original list : " + str (test_list))
res = list ( map ( lambda i: [test_list[i], '*' * (i + 1 )], range ( len (test_list))))
res = [elem for sublist in res for elem in sublist]
print ( "The increasing element pattern list : " + str (res))
|
Output
The original list : [1, 2, 3, 4, 5]
The increasing element pattern list : [1, '*', 2, '**', 3, '***', 4, '****', 5, '*****']
Time complexity: O(n)
Auxiliary space: O(n)
Similar Reads
Python - Alternate Minimum element in list
Some of the list operations are quite general and having shorthands without needing to formulate a multiline code is always required. Wanting to construct the list consisting of all the alternate elements of the original list is a problem that one developer faces in day-day applications and sometime
4 min read
Python - Check alternate peak elements in List
Given a list, the task is to write a Python program to test if it's alternate, i.e next and previous elements are either both smaller or larger across the whole list. Input : test_list = [2, 4, 1, 6, 4, 8, 0] Output : True Explanation : 4, 6, 8 are alternate and peaks (2 1). Input : test_list = [2,
3 min read
Python | Maximize alternate element List
The problem of getting maximum of a list is quite generic and we might some day face the issue of getting the maximum of alternate elements and get the list of 2 elements containing maximum of alternate elements. Letâs discuss certain ways in which this can be performed. Method #1 : Using list compr
3 min read
Python - Repeat Alternate Elements in list
Many times we have this particular use-case in which we need to repeat alternate element of list K times. The problems of making a double clone has been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Letâs discuss certain
7 min read
Python - Alternate list elements as key-value pairs
Given a list, convert it into dictionary by mapping alternate elements as key-value pairs. Input : test_list = [2, 3, 5, 6, 7, 8] Output : {3: 6, 6: 8, 2: 5, 5: 7} Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate] Input : test_list = [2, 3, 5, 6] Output : {3: 6,
2 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Insert after every Nth element in a list - Python
Inserting an element after every Nth item in a list is a useful way to adjust the structure of a list. For Example we have a list li=[1,2,3,4,5,6,7] Let's suppose we want to insert element 'x' after every 2 elements in the list so the list will look like li=[1,2,'x',3,4,'x',5,6,7] Iteration with ind
4 min read
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 min read
Python | Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
3 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3. Using index()index() method in Python searches for the first occu
3 min read