1

Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2. How to do it efficienlty with reasonable time and space complexity ?

my solution: using dictionary:

from collections import defaultdict


L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result

My desired output would be:

['e', 'd', 'i', 'r']

Can I get a better pythonic solution?

Thanks.

2
  • Please give an expected output sample for the same. Commented Mar 31, 2017 at 3:03
  • ['e', 'd', 'i', 'r'] Commented Mar 31, 2017 at 3:13

3 Answers 3

3

You can use the collection's counter class to simplify the code:

from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once

Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array.

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use python Counter for getting count of each word in the list. https://docs.python.org/2/library/collections.html#counter-objects

>>> L=['a','b','c','d','a','d','e','e','g','h']
>>> from collections import Counter
>>> c = Counter(L)
>>> c
Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1})

After doing this iterate over counter object and add elements to third list which have value 2.

Comments

0

This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time

set([x for x in L.extend(K) if L.extend(K).count(x) == 2])  

Notice that this returns a set and not a list!

2 Comments

This computes L.extend(K) twice, though. Add an extra line to compute that once.
Also, this mutates L. The original question didn't forbid that, but there's no reason to change inputs if you don't need to (especially when the question's focus is time and space efficiency).

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.