Python – Double each consecutive duplicate
Last Updated :
04 Feb, 2023
Sometimes, while working with data, we can have a problem in which we need to perform double of element on each consecutive occurrence of a duplicate. This is very specific problem, but solution to this can prove to be very handy. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way to perform this task. In this, we iterate each element and when we find duplicate we store in dictionary and perform its double subsequently.
Python3
test_list = [ 1 , 2 , 4 , 2 , 4 , 1 , 2 ]
print ("The original list is : " + str (test_list))
temp = {}
res = []
for ele in test_list:
temp[ele] = temp1 = temp.get(ele, 0 ) + ele
res.append(temp1)
print ("The list after manipulation is : " + str (res))
|
Output :
The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]
Time Complexity: O(n), where n is the number of elements in the list “test_list”. This is because the code iterates through the list “test_list” once and performs a constant amount of work for each element.
Auxiliary Space Complexity: O(n), where n is the number of elements in the list “test_list”. This is because the code uses a dictionary “temp” to store the frequency of elements in the list, which can take up to O(n) space in the worst-case scenario.
Method #2 : Using defaultdict() + loop This method performs this task in similar way as above. The only difference is a step is reduced by using defaultdict() as it pre initializes the list.
Python3
from collections import defaultdict
test_list = [ 1 , 2 , 4 , 2 , 4 , 1 , 2 ]
print ("The original list is : " + str (test_list))
temp = defaultdict( int )
res = []
for ele in test_list:
temp[ele] + = ele
res.append(temp[ele])
print ("The list after manipulation is : " + str (res))
|
Output :
The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]
Time complexity: O(n), where n is the number of elements in the test_list. This is because we are looping through the test_list once, which takes O(n) time.
Auxiliary space: O(n), because we are using a defaultdict of size n to store the elements.
Method #3 : Using for loop and count() method
Python3
test_list = [ 1 , 2 , 4 , 2 , 4 , 1 , 2 ]
print ( "The original list is : " + str (test_list))
res = []
for i in range ( 0 , len (test_list)):
x = test_list[:i + 1 ].count(test_list[i])
y = test_list[i]
res.append(x * y)
print ( "The list after manipulation is : " + str (res))
|
Output
The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]
Time Complexity : O(N)
Auxiliary Space : O(N)
Share your thoughts in the comments
Please Login to comment...