-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiset Implementation 7_15
84 lines (71 loc) · 2.23 KB
/
multiset Implementation 7_15
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/bin/python3
import math
import os
import random
import re
import sys
class Multiset:
multiset = {}
def add(self, val):
# adds one occurrence of val from the multiset, if any
print("START ADD")
if val in self.multiset:
self.multiset[val] += 1
print(val, "added in dict: ", self.multiset)
else:
self.multiset[val] = 1
print(val,"added to dict: ", self.multiset)
print("FINISH ADD")
pass
def remove(self, val):
print("START REMOVE")
# removes one occurrence of val from the multiset, if any
if val in self.multiset and self.multiset[val] > 1:
newVal = self.multiset.pop(val)
newVal -= 1
self.multiset[val] = newVal
print(val," removed: ", self.multiset)
elif val in self.multiset:
self.multiset.pop(val)
print(val, "remove from dic: ",self.multiset)
else:
print(val," not in dict")
print("FINISH REMOVE")
pass
def __contains__(self, val):
# returns True when val is in the multiset, else returns False
if val in self.multiset:
return True
return False
def __len__(self):
# returns the number of elements in the multiset
count = 0
for ele in self.multiset:
count += self.multiset[ele]
return count
if __name__ == '__main__':
def performOperations(operations):
m = Multiset()
result = []
for op_str in operations:
elems = op_str.split()
if elems[0] == 'size':
result.append(len(m))
else:
op, val = elems[0], int(elems[1])
if op == 'query':
result.append(val in m)
elif op == 'add':
m.add(val)
elif op == 'remove':
m.remove(val)
return result
q = int(input())
operations = []
for _ in range(q):
operations.append(input())
result = performOperations(operations)
fptr = open(os.environ['OUTPUT_PATH'], 'w')
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()