1

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.

4 Answers 4

4

If by array you mean list in python-:

s = ["a1","a2","a1","a3","a2"]
duplicates = [x for x in s if s.count(x) > 1]
myl = list(set(duplicates))
print myl

output ['a1', 'a2']

Sign up to request clarification or add additional context in comments.

Comments

1

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']    

Comments

0

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

Comments

0

Don't know about the performance though - but it works

s = ["a1","a2","a1","a3","a2"]
i=0
common=[]
for i in range(0,len(s)):
  if s[i] not in common and s[i] in s[i+1:]:
    common.append(s[i])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.