|
| 1 | +from linkedlist import LinkedList |
| 2 | + |
| 3 | +class Set(object): |
| 4 | + def __init__(self, elements=None): |
| 5 | + self.size = 0 |
| 6 | + if elements: |
| 7 | + self.buckets = [LinkedList() for i in range(len(elements))] |
| 8 | + for element in elements: |
| 9 | + self.add(element) |
| 10 | + else: |
| 11 | + self.buckets = [LinkedList() for i in range(init_size)] |
| 12 | + |
| 13 | + def __str__(self): |
| 14 | + pass |
| 15 | + |
| 16 | + def _bucket_index(self, item): |
| 17 | + """Hashes the item and returns the index of the bucket it is hashed to""" |
| 18 | + return hash(item) % len(self.buckets) |
| 19 | + |
| 20 | + def _load_factor(self): |
| 21 | + """ Returns the ratio of the number of items to the number of buckets """ |
| 22 | + return self.size / len(self.buckets) |
| 23 | + |
| 24 | + def get_items(self): |
| 25 | + return_list = [] |
| 26 | + for bucket in self.buckets: |
| 27 | + for item in bucket: |
| 28 | + return_list.append(item) |
| 29 | + return return_list |
| 30 | + |
| 31 | + |
| 32 | + def add(self, item): |
| 33 | + """Adds the specified item only if it is not only present in the Set""" |
| 34 | + if not self.contains(item): |
| 35 | + bucket_index = self._bucket_index(item) |
| 36 | + self.buckets[bucket_index].append(item) |
| 37 | + self.size += 1 |
| 38 | + |
| 39 | + def get(self, item): |
| 40 | + """Returns the specified items, returns None if not found """ |
| 41 | + bucket_index = self._bucket_index(item) |
| 42 | + return self.buckets[bucket_index].find(lambda value: value == item) |
| 43 | + |
| 44 | + def contains(self, item): |
| 45 | + bucket_index = self._bucket_index(item) |
| 46 | + return self.buckets[bucket_index].find(lambda value: value == item) is not None |
| 47 | + |
| 48 | + def is_subset(self, other): |
| 49 | + for bucket in self.buckets: |
| 50 | + for item in bucket.iterate(): |
| 51 | + if not other.contains(item): |
| 52 | + return False |
| 53 | + return True |
| 54 | + |
| 55 | + def union(self, other): |
| 56 | + new_set = Set() |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + A = Set(['a', 'b']) |
| 64 | + B = Set(['a', 'b', 'c']) |
| 65 | + A.add('b') |
| 66 | + print(A.is_subset(B)) |
| 67 | + print(B.is_subset(A)) |
0 commit comments