In [1]:
from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)
# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)
# This line will add a button to toggle visibility of code blocks, for use with the HTML export version
di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)
In [1]:
def count(f):
def counted(n):
counted.call_count += 1
return f(n)
counted.call_count = 0
return counted
In [3]:
class Link:
# __getitem__ is the built in Element selection []
# __len__ Built-in len function
empty = ()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __getitem__(self, i): # This is recursive
if i == 0:
return self.first
else:
return self.rest[i-1]
@count
def __len__(self):
return 1 + len(self.rest)
# Right now if you call a Link class it gives you this built-in repr
# string <__main__.Link instance at 0x104a693f8>
# Let's improve on that
def __repr__(self):
if self.rest:
rest_repr = ',' + repr(self.rest)
else:
rest_repr = ''
return 'Link({0}{1})'.format(self.first, rest_repr)
In [4]:
s = Link(3, Link(4, Link(5)))
In [5]:
len(s)
Out[5]:
In [6]:
s[0]
Out[6]:
In [7]:
s.__len__.call_count # To see that len function for our linked list is indeed recursive.
Out[7]:
In [14]:
s
Out[14]:
In [ ]: