|
10 | 10 | names_2 = f.read().split("\n") # List containing 10000 names |
11 | 11 | f.close() |
12 | 12 |
|
| 13 | +class BinarySearchTree: |
| 14 | + def __init__(self, value): |
| 15 | + self.value = value |
| 16 | + self.left = None |
| 17 | + self.right = None |
| 18 | + |
| 19 | + def insert(self, value): |
| 20 | + if value < self.value: |
| 21 | + if not self.left: |
| 22 | + self.left = BinarySearchTree(value) |
| 23 | + else: |
| 24 | + self.left.insert(value) |
| 25 | + |
| 26 | + elif value >= self.value: |
| 27 | + if not self.right: |
| 28 | + self.right = BinarySearchTree(value) |
| 29 | + else: |
| 30 | + self.right.insert(value) |
| 31 | + pass |
| 32 | + |
| 33 | +# searches the binary search tree for the input value, returning a boolean indicating whether the value exists in the tree or not. |
| 34 | + def contains(self, target): |
| 35 | + # compare target to root |
| 36 | + if target == self.value: |
| 37 | + print(f"target {target} == self.value {self.value}") |
| 38 | + return True |
| 39 | + # if it's smaller, check left side |
| 40 | + elif target < self.value: |
| 41 | + print(f"target {target} < self.value {self.value}") |
| 42 | + # first check that there is a left side; if not, return False |
| 43 | + if not self.left: |
| 44 | + print("no self.left") |
| 45 | + return False |
| 46 | + # else, if it doesn't match the left side, call contains on left side with same target |
| 47 | + elif target != self.left: |
| 48 | + print(f"target {target} != self.left {self.left}") |
| 49 | + return self.left.contains(target) |
| 50 | + else: |
| 51 | + print(f"target {target} == self.left {self.left}") |
| 52 | + return True |
| 53 | + # else, check right side |
| 54 | + elif target > self.value: |
| 55 | + print(f"target {target} > self.value {self.value}") |
| 56 | + # first check that there is a right side; if not, return False |
| 57 | + if not self.right: |
| 58 | + print("no self.right") |
| 59 | + return False |
| 60 | + # else, if it doesn't match the right side, call contains on right side with same target |
| 61 | + elif target != self.right: |
| 62 | + print(f"target {target} != self.right {self.right}") |
| 63 | + return self.right.contains(target) |
| 64 | + else: |
| 65 | + print(f"target {target} == self.right {self.right}") |
| 66 | + return True |
| 67 | + pass |
| 68 | + |
| 69 | +# 20.11 seconds |
13 | 70 | duplicates = [] |
14 | | -for name_1 in names_1: |
15 | | - for name_2 in names_2: |
16 | | - if name_1 == name_2: |
17 | | - duplicates.append(name_1) |
| 71 | +# for name_1 in names_1: |
| 72 | +# for name_2 in names_2: |
| 73 | +# if name_1 == name_2: |
| 74 | +# duplicates.append(name_1) |
| 75 | + |
| 76 | + |
18 | 77 |
|
19 | 78 | end_time = time.time() |
20 | 79 | print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") |
|
0 commit comments