-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclass_hashable.py
More file actions
42 lines (39 loc) · 1.15 KB
/
class_hashable.py
File metadata and controls
42 lines (39 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Container(object):
""" Holds hashable objects. Objects may occur 0 or more times """
def __init__(self):
""" Creates a new container with no objects in it. I.e., any object
occurs 0 times in self. """
self.vals = {}
def insert(self, e):
""" assumes e is hashable
Increases the number times e occurs in self by 1. """
try:
self.vals[e] += 1
except:
self.vals[e] = 1
def __str__(self):
s = ""
for i in sorted(self.vals.keys()):
if self.vals[i] != 0:
s += str(i)+":"+str(self.vals[i])+"\n"
return s
class ASet(Container):
def remove(self, e):
"""assumes e is hashable
removes e from self"""
try:
del(self.vals[e])
except:
return None
def is_in(self, e):
"""assumes e is hashable
returns True if e has been inserted in self and
not subsequently removed, and False otherwise."""
return e in self.vals
d1 = ASet()
d1.insert(4)
print(d1.is_in(4))
d1.insert(5)
print(d1.is_in(5))
d1.remove(5)
print(d1.is_in(5))