Demoing language features

The great thing is that now the person you share this notebook with can easily tweak and play with the examples you send them. You've created a little sandbox.

Sets

Sets are a powerful feature of python that many people coming from other languages aren't aware of. They are much more efficient than dictionaries/hashes when you're just trying to keep track of if you've seen an item or not, and not track any values with them.


In [ ]:
set1 = {'peter', 'peter', 'paul', 'mary'}
set2 = {'dave', 'amanda', 'kelly', 'paul'}
set3 = {'orange', 'black', 'red', 'blue'}
print "union: " + str(set1.union(set2))
print "intersection: " + str(set1.intersection(set2))
print "difference: " + str(set1.difference(set2))
print "isdisjoint set1/set2: " + str(set1.isdisjoint(set2))
print "isdisjoint set1/set3: " + str(set1.isdisjoint(set3))
print "issubset: " + str(set1.issubset(set2))
print "issuperset: " + str(set1.issuperset(set2))

You can use these operations on dictionaries if you need to find areas where they are similar and different, for example:


In [ ]:
dict1 = { 'tom': 'jones', 'stewart': 'copeland', 'marty': 'mcfly'}
dict2 = { 'tom': 'sellek', 'sasha': 'baron cohen'}

for key in set(dict1.keys()).difference(dict2.keys()):
    print "'{}': '{}' did not appear in dict2".format(key, dict1[key])

Tests are good for mentorship

Using the ipython_doctester extension, you can actually write small tests right inline in the code. This can also be useful for making your notebooks 'auditable', showing inline the test cases used to check a conversion method.


In [ ]:
from ipython_doctester import test


@test
def square(x):
    '''
    >>> square(2)
    4
    >>> square(3)
    9
    
    # intentionally show a failing test
    >>> square(4)
    17
    '''
    return x ** 2

In [ ]: