Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Double each consecutive duplicate

Improve Article
Save Article
  • Last Updated : 26 Dec, 2022
Improve Article
Save Article

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




# Python3 code to demonstrate
# Double each consecutive duplicate
# using loop
 
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Double each consecutive duplicate
# using loop
temp = {}
res = []
for ele in test_list:
    temp[ele] = temp1 = temp.get(ele, 0) + ele
    res.append(temp1)
     
# printing result
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]

  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




# Python3 code to demonstrate
# Double each consecutive duplicate
# using loop + defaultdict()
from collections import defaultdict
 
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Double each consecutive duplicate
# using loop + defaultdict()
temp = defaultdict(int)
res = []
for ele in test_list:
    temp[ele] += ele
    res.append(temp[ele])
     
# printing result
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]

Method #3 : Using for loop and count() method

Python3




# Python3 code to demonstrate
# Double each consecutive duplicate
# using loop
 
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Double each consecutive duplicate
# using loop
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)
 
     
# printing result
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)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!