Program to define set data structure without using library set class in Python


Suppose we want to implement a set data structure with the following methods −

  • Constructor to construct a new instance of a set
  • add(val) to insert integer val into the set
  • exists(val) to check whether val is in the set or not
  • remove(val) to remove the val from the set

So, if we construct a set s, then call s.add(10), s.add(20), s.add(10), s.exists(10), s.remove(10), s.exists(10), s.exists(20), then the output will be

  • for s.add(10) it will insert 10
  • for s.add(20) it will insert 20
  • 10 is already in s, so nothing will happen
  • s.exists(10) will return true as 10 is there
  • Delete 10 by s.remove(10)
  • s.exists(10) will return false because 10 is removed and one element can be there only once
  • s.exists(20) will return true as 20 is present there.

To solve this, we will follow these steps −

  • Define constructor.
  • buckets := an empty map and this will hold a list of data
  • Define a function add() . This will take val
  • if exists(val) is false, then
    • insert val at the end of buckets[val]
  • Define a function exists() . This will take val
  • return true when val is in buckets[val], otherwise false
  • Define a function remove(). This will take val
  • delete buckets[val]

Example

Let us see the following implementation to get better understanding −

from collections import defaultdict
class MySet:
   def __init__(self):
      self.buckets = defaultdict(list)

   def add(self, val):
      if not self.exists(val):
         self.buckets[val].append(val)

   def exists(self, val):
      return val in self.buckets[val]

   def remove(self, val):
      del self.buckets[val]

s = MySet()
s.add(10)
s.add(20)
s.add(10)
print(s.exists(10))
s.remove(10)
print(s.exists(10))
print(s.exists(20))

Input

s = MySet()
s.add(10)
s.add(20)
s.add(10)
s.exists(10)
s.remove(10)
s.exists(10)
s.exists(20)

Output

True
False
True

Updated on: 14-Oct-2021

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements