|
| 1 | +""" |
| 2 | +Symmetric Difference |
| 3 | +Given two arrays, return a new array containing the symmetric difference of them. |
| 4 | +
|
| 5 | +The symmetric difference between two sets is the set of values that appear in either set, but not both. |
| 6 | +Return the values in the order they first appear in the input arrays. |
| 7 | +
|
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +import unittest |
| 12 | + |
| 13 | +class SymmetricDifferenceTest(unittest.TestCase): |
| 14 | + |
| 15 | + def test1(self): |
| 16 | + self.assertEqual(difference([1, 2, 3], [3, 4, 5]), [1, 2, 4, 5]) |
| 17 | + |
| 18 | + def test2(self): |
| 19 | + self.assertEqual(difference(["a", "b"],["c", "b"]),["a", "c"]) |
| 20 | + |
| 21 | + def test3(self): |
| 22 | + self.assertEqual(difference([1, "a", 2],[2, "b", "a"]), [1, "b"]) |
| 23 | + |
| 24 | + def test4(self): |
| 25 | + self.assertEqual(difference([1, 3, 5, 7, 9],[1, 2, 3, 4, 5, 6, 7, 8, 9]),[2, 4, 6, 8]) |
| 26 | + |
| 27 | +def difference(arr1, arr2): |
| 28 | + """ |
| 29 | + The Limitations for this approach are |
| 30 | + The block of code will include duplicates if the same unique item appears multiple times in |
| 31 | + one array but not in the other. |
| 32 | + example: |
| 33 | + print(difference([1, 1, 2],[2, 3])) |
| 34 | + # Output: [1, 1, 3] ( but expected [1, 3]) |
| 35 | +
|
| 36 | + 1. Because both 1's from arr1 get appended. |
| 37 | + 2. Efficiency : Each item not in arr2 check is an O(n) membership test on a list. For large arrays, this become slow. |
| 38 | + Using sets would be faster. |
| 39 | +
|
| 40 | + """ |
| 41 | + |
| 42 | + result = [] |
| 43 | + |
| 44 | + for item in arr1: |
| 45 | + if item not in arr2: |
| 46 | + result.append(item) |
| 47 | + |
| 48 | + for item in arr2: |
| 49 | + if item not in arr1: |
| 50 | + result.append(item) |
| 51 | + |
| 52 | + return result |
| 53 | + |
| 54 | +def difference(arr1, arr2): |
| 55 | + result = [] |
| 56 | + seen = set() |
| 57 | + |
| 58 | + for item in arr1: |
| 59 | + if item not in arr2 and item not in seen: |
| 60 | + result.append(item) |
| 61 | + seen.add(item) |
| 62 | + |
| 63 | + for item in arr2: |
| 64 | + if item not in arr1 and item not in seen: |
| 65 | + result.append(item) |
| 66 | + seen.add(item) |
| 67 | + |
| 68 | + |
| 69 | + return result |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + print(difference([1,1,3], [2, 3, 5])) |
| 78 | + # unittest.main() |
0 commit comments