Python – Random insertion of elements K times
Last Updated :
17 May, 2023
Given 2 list, insert random elements from List 2 to List 1, K times at random position.
Input : test_list = [5, 7, 4, 2, 8, 1], add_list = [“Gfg”, “Best”, “CS”], K = 2 Output : [5, 7, 4, 2, 8, 1, ‘Best’, ‘Gfg’] Explanation : Random elements from List 2 are added 2 times. Input : test_list = [5, 7, 4, 2, 8, 1], add_list = [“Gfg”, “Best”, “CS”], K = 1 Output : [5, 7, 4, 2, 8, 1, ‘Gfg’] Explanation : Random elements from List 2 are added 1 times.
Method : Using randint() + list slicing + loop + choice()
In this, choice() is used to get random elements from list 2 to insert into list 1 and, randint() is used to get index at which this needs to be inserted. Then list slicing is used to remake list according to newer order.
Python3
import random
test_list = [ 5 , 7 , 4 , 2 , 8 , 1 ]
print ( "The original list : " + str (test_list))
add_list = [ "Gfg" , "Best" , "CS" ]
K = 3
for idx in range (K):
index = random.randint( 0 , len (test_list))
test_list = test_list[:index] + [random.choice(add_list)] + test_list[index:]
print ( "The created List : " + str (test_list))
|
Output
The original list : [5, 7, 4, 2, 8, 1]
The created List : ['CS', 'CS', 5, 7, 4, 'CS', 2, 8, 1]
Time complexity: O(n*n), where n is the length of the test_list. The randint() + list slicing + loop + choice() takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required
Method #2: Using random.choice()
step-by-step approach :
1. Define the function insert_random_elements which takes three arguments: test_list, add_list, and K.
2. Create a range object range_obj that contains the indices where new elements can be inserted. The range object should span from 0 to the length of test_list plus K.
3. Loop over K times.
4. Generate a random index rand_index using random.choice(range_obj) to randomly select an index from range_obj.
5. Insert a random element from add_list into test_list at the randomly chosen index.
6. Return the modified test_list.
Python3
import random
def insert_random_elements(test_list, add_list, K):
range_obj = range ( len (test_list) + K)
for i in range (K):
rand_index = random.choice(range_obj)
test_list.insert(rand_index, random.choice(add_list))
return test_list
test_list = [ 5 , 7 , 4 , 2 , 8 , 1 ]
add_list = [ "Gfg" , "Best" , "CS" ]
K = 3
print (insert_random_elements(test_list, add_list, K))
|
Output
[5, 7, 4, 'Best', 'Best', 2, 8, 1, 'Best']
time complexity: O(K^2)
space complexity: O(1)
Method #3: Using numpy:
Algorithm:
- Create a for loop to iterate K times.
- Generate a random index between 0 and len(test_list) – 1.
- Save the element at the random index to a variable called old_element.
- Choose a random element from add_list and set it as the element at the random index in test_list.
- Insert old_element after the new element at the random index.
- Return the modified test_list with randomly inserted elements.
Python3
import random
import numpy as np
def insert_random_elements(test_list, add_list, K):
for i in range (K):
rand_index = random.randint( 0 , len (test_list) - 1 )
old_element = test_list[rand_index]
new_element = np.random.choice(add_list)
test_list[rand_index] = new_element
test_list.insert(rand_index + 1 , old_element)
return test_list
test_list = [ 5 , 7 , 4 , 2 , 8 , 1 ]
add_list = [ "Gfg" , "Best" , "CS" ]
K = 3
print (insert_random_elements(test_list, add_list, K))
|
Output:
[5, 7, 4, ‘Gfg’, ‘CS’, ‘CS’, 2, 8, 1]
Time complexity:
Generating a random index using random.randint(0, len(test_list) – 1) takes O(1) time.
Choosing a random element from add_list using np.random.choice(add_list) takes O(1) time.
Inserting a new element into test_list at a given index using insert() takes O(n) time, where n is the length of test_list.
Therefore, the overall time complexity of the insert_random_elements() function is O(K * n), where K is the number of random elements to insert and n is the length of test_list.
Auxiliary Space:
The function uses O(K) additional space to store the old_element variable for each insertion.
The function also modifies the input test_list in place, so the space complexity for that is O(1).
Therefore, the overall space complexity of the insert_random_elements() function is O(K).
Approach#4: Using lambda+map
Create a list of random elements from add_list using the map() function and lambda function. Append the generated list to the original test_list using the + operator. Return the resultant list.
Algorithm
1. Initialize the test_list, add_list and K values.
2. Generate a list of K random elements from the add_list using map() function and lambda function.
3. Append the generated list to the test_list using + operator.
4. Return the resultant list.
Python3
import random
test_list = [ 5 , 7 , 4 , 2 , 8 , 1 ]
add_list = [ "Gfg" , "Best" , "CS" ]
K = 2
result_list = test_list + list ( map ( lambda x: random.choice(add_list), range (K)))
print (result_list)
|
Output
[5, 7, 4, 2, 8, 1, 'Best', 'CS']
Time Complexity: O(K), as the time complexity of generating a list of K random elements using map() function and lambda function is O(K) and appending two lists using + operator takes O(n) time where n is the length of the list.
Auxiliary Space: O(K), as the space complexity of generating a list of K random elements using map() function and lambda function is O(K) and the space complexity of storing the resultant list is also O(K).
Similar Reads
Python - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. [Tex]Index Rank of Number = (Sum of occurrence indices of number) / number[/Tex] Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6),
3 min read
Python | Return new list on element insertion
The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let's discuss certain ways in which this task can be perform
5 min read
Python | Remove random element from list
Sometimes, while working with Python lists, we can have a problem or part of it, in which we desire to convert a list after deletion of some random element. This can have it's application in gaming domain or personal projects. Let's discuss certain way in which this task can be done. Method : Using
3 min read
Repeat Each Element K times in List - Python
The task of repeating each element k times in a list in Python involves creating a new list where each element from the original list appears k times consecutively. For example, given the list a = [4, 5, 6] and k = 3, the goal is to produce [4, 4, 4, 5, 5, 5, 6, 6, 6]. Using list comprehensionList c
3 min read
Python - N Random Tuples list
Sometimes, while working with Python records, we can have a problem in which we need to construct a random tuple list. This can have applications in many domains using gaming and day-to-day programming. Let's discuss specific ways in which this task can be performed in Python. Input: N = 4 R = 6 Out
3 min read
Python - Generate Random String of given Length
Generating random strings is a common requirement for tasks like creating unique identifiers, random passwords, or testing data. Python provides several efficient ways to generate random strings of a specified length. Below, weâll explore these methods, starting from the most efficient. Using random
2 min read
Python - Generate k random dates between two other dates
Given two dates, the task is to write a Python program to get K dates randomly. Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7 Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6,
4 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collection
5 min read
Python | N element incremental tuples
Sometimes, while working with data, we can have a problem in which we require to gather a data that is of the form of sequence of increasing element tuple with each tuple containing the element N times. Let's discuss certain ways in which this task can be performed. Method #1 : Using generator expre
5 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read