-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASet container.py
More file actions
52 lines (45 loc) · 1.28 KB
/
ASet container.py
File metadata and controls
52 lines (45 loc) · 1.28 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
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 10:15:40 2017
@author: thelma
"""
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 KeyError:
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.keys()
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))