Python program to Mark duplicate elements in string
Given a list, the task is to write a Python program to mark the duplicate occurrence of elements with progressive occurrence number.
Input : test_list = [‘gfg’, ‘is’, ‘best’, ‘gfg’, ‘best’, ‘for’, ‘all’, ‘gfg’]
Output : [‘gfg1’, ‘is’, ‘best1’, ‘gfg2’, ‘best2’, ‘for’, ‘all’, ‘gfg3’]
Explanation : gfg’s all occurrence are marked as it have multiple repetitions(3).
Input : test_list = [‘gfg’, ‘is’, ‘best’, ‘best’, ‘for’, ‘all’]
Output : [‘gfg’, ‘is’, ‘best1’, ‘best2’, ‘for’, ‘all’]
Explanation : best’s all occurrence are marked as it have multiple repetitions(2).
Method 1: Using count() + enumerate() + list comprehension + slicing
In this, in order to get the duplicate count, the list is sliced to current element index, and count of occurrence of that element till current index is computed using count() and append.
Python3
test_list = [ "gfg" , "is" , "best" , "gfg" ,
"best" , "for" , "all" , "gfg" ]
print ( "The original list is : " + str (test_list))
res = [val + str (test_list[:idx].count(val) + 1 ) if test_list.count(val) > 1 else val for idx,
val in enumerate (test_list)]
print ( "Duplicates marked List : " + str (res))
|
Output:
The original list is : [‘gfg’, ‘is’, ‘best’, ‘gfg’, ‘best’, ‘for’, ‘all’, ‘gfg’]
Duplicates marked List : [‘gfg1’, ‘is’, ‘best1’, ‘gfg2’, ‘best2’, ‘for’, ‘all’, ‘gfg3’]
Time Complexity: O(n)
Auxiliary Space : O(n)
Method 2: Using map() + count() + lambda
Similar to the above method, the only difference being map() is used to get a function using lambda to extend to whole list elements.
Python3
test_list = [ "gfg" , "is" , "best" , "gfg" ,
"best" , "for" , "all" , "gfg" ]
print ( "The original list is : " + str (test_list))
res = list ( map ( lambda ele: ele[ 1 ] + str (test_list[ : ele[ 0 ]].count(ele[ 1 ]) + 1 ) if test_list.count(ele[ 1 ]) > 1 else ele[ 1 ],
enumerate (test_list)))
print ( "Duplicates marked List : " + str (res))
|
Output:
The original list is : [‘gfg’, ‘is’, ‘best’, ‘gfg’, ‘best’, ‘for’, ‘all’, ‘gfg’]
Duplicates marked List : [‘gfg1’, ‘is’, ‘best1’, ‘gfg2’, ‘best2’, ‘for’, ‘all’, ‘gfg3’]
The Time and Space Complexity of all the methods is :
Time Complexity: O(n)
Space Complexity: O(n)
Method #3: Using operator.countOf() method
Python3
import operator as op
test_list = [ "gfg" , "is" , "best" , "gfg" ,
"best" , "for" , "all" , "gfg" ]
print ( "The original list is : " + str (test_list))
res = [val + str (op.countOf(test_list[:idx], val) + 1 ) if op.countOf(test_list, val) > 1 else val for idx,
val in enumerate (test_list)]
print ( "Duplicates marked List : " + str (res))
|
Output
The original list is : ['gfg', 'is', 'best', 'gfg', 'best', 'for', 'all', 'gfg']
Duplicates marked List : ['gfg1', 'is', 'best1', 'gfg2', 'best2', 'for', 'all', 'gfg3']
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
01 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...