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
suseunionwith anotherSet:s.union(Set(1)) r = Set(2,3) s.union(r)To check if
scontains an element:if 1 in s: # Do somethingTo 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 eInitializes a
SetinO(1)time.Args
initial_elements- To initialize the
Setto 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
Setthat occur in another set. Callings.difference(Set(1))on aSetsis akin tos = s - {1}. This runs inO(n)time wherenis the size of the otherSet.Args
other_set- Another
Setspecifying the elements to be removed from thisSet. ThisSetis unaffected by this method.
Raises
TypeError- If
other_setis 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
Setinto thisSetthat do not already exist in thisSet. Callings.union(Set(1))on aSetsis akin tos = s U {1}. This runs inO(n)time wherenis the size of the otherSet.Args
other_set- Another
Setspecifying the elements to be added to thisSetif they do not already exist. ThisSetis unaffected by this method.
Raises
TypeError- If
other_setis not aSet.