Skip to content

Commit adaacf3

Browse files
author
Catislin
committed
added some set code
1 parent 7019c47 commit adaacf3

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

source/Set.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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))

source/linkedlist.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,13 @@ def delete(self, item):
220220
# Otherwise raise an error to tell the user that delete has failed
221221
raise ValueError('Item not found: {}'.format(item))
222222

223+
def iterate(self):
224+
"""Iterate from the head of the list"""
225+
current = self.head
226+
while current:
227+
yield current.data
228+
current = current.next
229+
223230

224231
def test_linked_list():
225232
ll = LinkedList()

source/set_test.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import unittest
2+
3+
class SetTest(unittest.TestCase)
4+
def test_contains(self):

0 commit comments

Comments
 (0)