fork(1) download
  1. # Python 2.5 version
  2. from collections import defaultdict
  3.  
  4. def list_difference25(a, b):
  5. """Find (a - b) preserving duplicates and order."""
  6. # count items in a
  7. count = defaultdict(int) # item -> number of occurrences (no OrderedDict to avoid Python 2.7 dependency)
  8. for x in a:
  9. count[x] += 1
  10.  
  11. # remove items that are in b
  12. for x in b:
  13. count[x] -= 1
  14. diff = []
  15. for x in a:
  16. if count[x] > 0:
  17. count[x] -= 1
  18. diff.append(x)
  19. return diff
  20.  
  21. # Python 2.7 version
  22. from collections import Counter
  23.  
  24. def list_difference(a, b):
  25. count = Counter(a)
  26. count.subtract(b)
  27. diff = []
  28. for x in a:
  29. if count[x] > 0:
  30. count[x] -= 1
  31. diff.append(x)
  32. return diff
  33.  
  34. a, b = raw_input().split(), raw_input().split()
  35. print list_difference25(a, b)
  36. print list_difference(a, b)
Success #stdin #stdout 0.09s 8888KB
stdin
a b c b c 
a b c b
stdout
['c']
['c']