Python: Multiset Implementation | HackerRank Certification

Statement:

A multiset is the same as a set except that an element might occur more than once in a multiset. Implement a multiset data structure in Python. Given a template for the Multiset class. Implement 4 methods:

  • add(self,val): adds val to the multiset.
  • remove(self,val): if val is in the multiset, remove val from the multiset; otherwise do nothing.
  • _contains_(self,val): returns True if the cal is in the multiset; otherwise it returns False.
  • _len_(self): returns the number of elements in the multiset.
Additional methods are allowed as necessary.

The implementation of the 4 required methods will be tested by a provided code stub on several input files. Each input file contains several operations, each of one of the below types. Values returned by query and size operations are appended to a result list, which is printed as the output by the provided code stub.


Solution:


 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
class Multiset:
    global multiset
    multiset=[]
    def add(self, val):
        # adds one occurrence of val from the multiset, if any
        self.val=val
        multiset.append(val)
        #print(multiset)
    def remove(self, val):
        # removes one occurrence of val from the multiset, if any
        self.val=val
        leng=len(multiset)

        if leng!=0 and val in multiset:
            m=multiset[leng-1]
            multiset.remove(val)
            #print(multiset)
        else:
            pass
    def __contains__(self, val):
        # returns True when val is in the multiset, else returns False
        self.val=val
        if self.val in multiset:
            return True
        else:
            return False

    def __len__(self):
        # returns the number of elements in the multiset
        return len(multiset)

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()


                   

    


Labels : #hackerrank certification ,#python (basic) ,

Post a Comment