Teaching Kids Programming: Videos on Data Structures and Algorithms
A Set is a data structure to hold unique elements in a collection. In Python we can use set() to create an empty set or use set(list) to create a set from a given list.
Set Operations
Create a Set
1 2 | a = set() b = set([1, 2, 3, 3, 2]) |
a = set() b = set([1, 2, 3, 3, 2])
Add and Remove element from a Set
remove an none-existent element from the set will raise exception. Use discard() method if we want to suppress the exception.
1 2 3 | a = set() a.add(1) a.remove(1) |
a = set() a.add(1) a.remove(1)
Union Two Sets
1 2 | a.union(b) #or a|b |
a.union(b) #or a|b
Intersection of Two Sets
1 2 | a.intersect(b) # a&b |
a.intersect(b) # a&b
Symmetric Difference of Two Sets
1 2 | a.symmetric_difference(b) # a^b |
a.symmetric_difference(b) # a^b
Difference of a Set to another
Compute the elements in a but not in b
1 2 | a.difference(b) # or a-b |
a.difference(b) # or a-b
Common Elements in Both Sets?
isdisjoint returns true if both sets have no elements in common. We can also use the len to check the size of the intersection of two sets.
1 2 | a.isdisjoint(b) # or len(a&b) == 0 |
a.isdisjoint(b) # or len(a&b) == 0
Venn Graph
Check if a String has all Unique Characters?
Traditional approach, using a set to record the characters that have appeared in the string and fail the check if we find one already in the set:
1 2 3 4 5 6 7 | def unique(s): st = set() for i in s: if i in st: return False st.add(i) return True |
def unique(s): st = set() for i in s: if i in st: return False st.add(i) return True
A quicker/smarter way to do this would be to build a set from the characters and check the sizes of the set and the string: same if string contains all unique characters
1 2 | def unique(s) return len(set(list(s))) == len(s) |
def unique(s) return len(set(list(s))) == len(s)
–EOF (The Ultimate Computing & Technology Blog) —
a WordPress rating system
Last Post: Diagonal Sorting Algorithm in a Matrix
Next Post: Algorithm to Swap Consecutive Pair of Even Numbers