Wednesday, October 5, 2016

[ Functional Programming ] Sets

Sets
 => a data structures , similar to lists or dictionaries.
=> created using curly braces , or the set function
=> they can also use "in" to check whether they contain a particular item. ~ lists
=> len ~ lists
=> to create empty set , use set()


>>>
num_set = {1,2,3,4,5}
word_set = set(["a","b","c"])

print ( 3 in num_set)
print ("a" not  in word_set)

>>>
True
False

What are the difference between set and list ?
=> set , are unordered , that they can;t be indexed
=>set , cannot contain duplicate elements
=>set , instead of using append , use add
=>set , remove method removes a specific element , from set , pop removes arbitrary element

>>>
nums = {1,2,1,3,1,4,5,6}
print(nums)
nums.add(-7)
nums.remove(3)
print(nums)

>>>
{1,2,3,4,5,6}
{1,2,4,5,6,-7}


Sets can be combined using mathematical operations.
=> union
=> intersection &
=> difference
=> symmetric difference


>>>
first = {1,2,3,4,5,6}
second = {4,5,6,7,8,9}

print (first | second)
print (first & second)
print (first - second)
print (second - first)
print (first ^ second)


>>>
{1,2,3,4,5,6,7,8,9}
{4,5,6}
{1,2,3}
{7,8,9}
{1,2,3,7,8,9}

Python support data structure
 => list , dictionary , tuple , set

<dictionary>
=> need a logical association between a key:value pair
=> fast lookup for your data based on custom key
=> when your data is being constantly modified . (dictionaries are mutable)

<list>
=> if you have a collection of data that does not need random access
=> for simple , iterable , collection

<set>
=> need uniqueness for the elements

<tuples>
=> data cannot change

No comments:

Post a Comment