Given a List, replace first K elements by N.
Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3
Output : [3, 3, 3, 3, 4, 2, 6, 9]
Explanation : First 4 elements are replaced by 3.
Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10
Output : [10, 10, 6, 8, 4, 2, 6, 9]
Explanation : First 2 elements are replaced by 10.
OutputThe original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
OutputThe original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Initially convert each element of list to string and then join the list using empty string.Replace first K characters with N in that joined list(which is a string) ,later convert each element of a string to integer and make it a list.
OutputThe original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
OutputThe original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Initializing the list takes O(n) time, where n is the length of the list.
Initializing K and N takes constant time, i.e., O(1).
The for loop that iterates over the first K elements takes O(K) time.
The list comprehension takes O(K) time.
Printing the updated list takes O(n) time.
Therefore, the overall time complexity is O(n + K).
Space complexity:
The space required to store the input list test_list is O(n).
The space required to store the variables K and N is constant, i.e., O(1).
The space required by the list comprehension is also O(n).
Therefore, the overall space complexity is O(n).
Initialize the list test_list.
Initialize the values of K and N.
Use list slicing to select the sublist of test_list up to index K.
Replace the selected sublist with a list of K copies of N using the = assignment operator and the * operator.
Print the resulting list.
OutputElements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]