Importing a web notebook

Python scripts can be imported as a web notebook. Obviously, we can also import previously exported notebooks.

How to do it...

The following steps show how a python script can be imported as a web notebook:

  1. Import a python script by dragging it from Explorer or Finder into the notebook page. The following screenshot is an example of what we see after dragging the vectorsum.py from NumPy Beginner's Guide into the notebook page:
    How to do it...
  2. Click the Upload button to import the program. IPython does a decent job of importing the code. Unfortunately, as shown in the following screenshot, the code is all placed in one cell. At least that is how it worked at the time of writing:
    How to do it...
  3. Tag the script for multiple cells.

    In order to split the code into multiple cells we need to use special tags. These tags are in fact Python comments, but they look a bit like XML tags. The code has to start with the following tag:

    # <nbformat>2</nbformat>

    This indicates the format of the notebook. Each new code cell is indicated with the following tag:

    # <codecell>

    The following is the tagged code:

    # <nbformat>2</nbformat>
    #!/usr/bin/env/python
    
    from datetime import datetime
    import numpy
    """
     Chapter 1 of NumPy Beginners Guide.
     This program demonstrates vector addition the Python way.
     Run from the command line as follows
         
      python vectorsum.py n
     
     where n is an integer that specifies the size of the vectors.
    
     The first vector to be added contains the squares of 0 up to n. 
     The second vector contains the cubes of 0 up to n.
     The program prints the last 2 elements of the sum and the elapsed time.
    """
    
    def numpysum(n):
       a = numpy.arange(n) ** 2
       b = numpy.arange(n) ** 3
       c = a + b
    
       return c
    
    def pythonsum(n):
       a = range(n)
       b = range(n)
       c = []
    
       for i in range(len(a)):
           a[i] = i ** 2
           b[i] = i ** 3
           c.append(a[i] + b[i])
    
       return c
       
    # <codecell>
    size = int(50)
    
    # <codecell>
    start = datetime.now()
    c = pythonsum(size)
    delta = datetime.now() - start
    print "The last 2 elements of the sum", c[-2:]
    print "PythonSum elapsed time in microseconds", delta.microseconds
    
    # <codecell>
    start = datetime.now()
    c = numpysum(size)
    delta = datetime.now() - start
    print "The last 2 elements of the sum", c[-2:]
    print "NumPySum elapsed time in microseconds", delta.microseconds

    The code is split into several cells according to the tags, as shown in the following screenshot:

    How to do it...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset