Module dalpy.sets
Module that holds classes related to sets.
This module contains the Set
class. Set
represents a set.
Examples
Creating a Set
, adding elements, and checking membership:
s = Set()
s.union(Set(1))
s.union(Set(2,3))
if 1 in s:
print("1")
Removing elements from a Set
:
t = Set(3,4)
s.difference(t)
Classes
class Set (*initial_elements)
-
Represents a set.
This class represents a set that preserves insertion order. This allows for it to be used in cases where the order of the set's contents must be deterministic.
Examples
To initialize an empty
Set
:s = Set()
To add elements to
s
useunion
with anotherSet
:s.union(Set(1)) r = Set(2,3) s.union(r)
To check if
s
contains an element:if 1 in s: # Do something
To remove a Set of elements from
s
, make use of difference:t = Set(2,3) s.difference(t)
To remove one element from
s
, make use of the ability to create a singleton set combined with difference:s.difference(Set(1))
To iterate over a
Set
:for e in s: # Do something with e
Initializes a
Set
inO(1)
time.Args
initial_elements
- To initialize the
Set
to contain some elements, pass any number of arguments separated by commas that will be passed via this variable length arguments parameter.
Methods
def difference(self, other_set)
-
Performs a set difference operation on this
Set
.This method removes all the elements from this
Set
that occur in another set. Callings.difference(Set(1))
on aSet
s
is akin tos = s - {1}
. This runs inO(n)
time wheren
is the size of the otherSet
.Args
other_set
- Another
Set
specifying the elements to be removed from thisSet
. ThisSet
is unaffected by this method.
Raises
TypeError
- If
other_set
is not aSet
.
def is_empty(self)
def size(self)
def union(self, other_set)
-
Performs a set union operation on this
Set
.This method adds all the elements from another
Set
into thisSet
that do not already exist in thisSet
. Callings.union(Set(1))
on aSet
s
is akin tos = s U {1}
. This runs inO(n)
time wheren
is the size of the otherSet
.Args
other_set
- Another
Set
specifying the elements to be added to thisSet
if they do not already exist. ThisSet
is unaffected by this method.
Raises
TypeError
- If
other_set
is not aSet
.