Saturday, March 8, 2014

Python Study Note: Data Structure - Set

"A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference."

This is pretty much about a "set". Set is a simple object, it could be very helpful to used as a "check-existence" or "eliminate duplicates" tool.

1. Generate set
    1.1 From List or tuple
        a = [1,2,3]; b = (4,5,6); c = set(a); c = set(b)

    Here there is one interesting fact, the elements in a set should be "hashable"(which means "An object is hashable if it has a hash value which never changes during its lifetime"). Since a "list"'s value could be changed, it may be only a pointer, so one cannot include a "list" as an entry in a set; but one can include a "tuple" as an element of a set.

2. Usage
    2.1 "check-existence"
        a = range(10); b = set(a);
        10 in c
    2.2 "eliminate duplicates"
        a = [1,2,3,1,2,5,2,10]; b = set(a); c = list(b);

3. Evaluation
    3.1 len(s); x in s; x not in s;         --- whether element inside set
    3.2 s.issubset(t); s.issuperset(t)   --- whether set s is sub/super set of t
    3.3 s.union(t)                 ---  equivalent to s | t
    3.4 s.intersection(t)       --- equivalent to s & t
    3.5 s.difference(t)         --- equivalent to s - t
    3.6 s.symmetric_difference(t)    --- new set with elements in either s or t but not both
    3.7 s.copy()        --- new set with a shadow copy of s

4. Operator
    4.1 s.update(t)   --- return set s with elements added from t
    4.2 s.difference_update(t) --- return set s after removing elements found in t
    4.3 s.intersection_update(t) --- return set s keeping only elements also found in t
    4.4 s.symmetric_difference_update(t)
    4.5 s.add(x)
    4.6 s.remove(x); s.discard(x) --- if there is no such element, remove return error, while discard does not
    4.7 s.pop() --- remove and return an arbitrary element from s; or error if not ..
    4.8 s.clear() -- remove all elements from a set

No comments:

Post a Comment