I have an array of strings as follow:
[a1,a2,a1,a3,a2]
I want to find the similar strings and put them in to a new array as below:
[a1,a2]
I am new to Python. Please give me an idea on how to do this.
Thanks.
An alternate solution using collections.Counter
s = ["a1","a2","a1","a3","a2"]
c=collections.Counter(s)
print dict(c.most_common(len(c)-1)).keys()
['a1', 'a2']
Here is O(nlog(n)) approach to find duplicates. Initial list is sorted ( O(nlog(n)) ) so that duplicate elements in adjacent places. Then simple O(n) iteration is possible to find duplicates.
s = ["a1","a2","a1","a3","a2"]
s.sort() # sort changes initial list
new_list = []
prev = (None, False)
for x in s:
if prev == (x, False):
new_list.append(x)
prev = (x, True)
else:
prev = (x, False)
print new_list