I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
TabWidget
Can you write Python code for it?

name = widgets.Text(description='Name:', padding=4)
color = widgets.Dropdown(description='Color:', padding=4, options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
page1 = widgets.Box(children=[name, color], padding=4)

age = widgets.IntSlider(description='Age:', padding=4, min=0, max=120, value=50)
gender = widgets.RadioButtons(description='Gender:', padding=4, options=['male', 'female'])
page2 = widgets.Box(children=[age, gender], padding=4)

tabs = widgets.Tab(children=[page1, page2])
display(tabs)

tabs.set_title(0, 'Name')
tabs.set_title(1, 'Details')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
Using hbox
To make widgets display horizontally, they can be children of an HBox widget.
Can you write Python code for it?

container = widgets.HBox(children=buttons)
display(container)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/.ipynb_checkpoints/5 - Widget Styling-checkpoint.ipynb".
The first task is:
Visibility
The visible property of widgets can be used to hide or show widgets that have already been displayed (as seen below).  The visible property can be:
* True - the widget is displayed
* False - the widget is hidden, and the empty space where the widget would be is collapsed
* None - the widget is hidden, and the empty space where the widget would be is shown
Can you write Python code for it?

w1 = widgets.Latex(value="First line")
w2 = widgets.Latex(value="Second line")
w3 = widgets.Latex(value="Third line")
display(w1, w2, w3)

w2.visible=None

w2.visible=False

w2.visible=True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
Function traitlets.link and traitlets.dlink return a Link or DLink object. The link can be broken by calling the unlink method.
Can you write Python code for it?

# May get an error depending on order of cells being run!
l.unlink()
dl.unlink()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
Function widgets.jslink returns a Link widget. The link can be broken by calling the unlink method.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
Linking Widgets
Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events.
Linking traitlets attributes from the server side
The first method is to use the link and dlink functions from the traitlets module.
Can you write Python code for it?

import traitlets

# Create Caption
caption = widgets.Label(value = 'The values of slider1 and slider2 are synchronized')

# Create IntSlider
slider1 = widgets.IntSlider(description='Slider 1')
slider2 =  widgets.IntSlider(description='Slider 2')

# Use trailets to link
l = traitlets.link((slider1, 'value'), (slider2, 'value'))

# Display!
display(caption, slider1, slider2)

# Create Caption
caption = widgets.Label(value = 'Changes in source values are reflected in target1')

# Create Sliders
source = widgets.IntSlider(description='Source')
target1 = widgets.IntSlider(description='Target 1')

# Use dlink
dl = traitlets.dlink((source, 'value'), (target1, 'value'))
display(caption, source, target1)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
Linking widgets attributes from the client side
When synchronizing traitlets attributes, you may experience a lag because of the latency due to the roundtrip to the server side. You can also directly link widget attributes in the browser using the link widgets, in either a unidirectional or a bidirectional fashion.
Can you write Python code for it?

# NO LAG VERSION
caption = widgets.Label(value = 'The values of range1 and range2 are synchronized')

range1 = widgets.IntSlider(description='Range 1')
range2 =  widgets.IntSlider(description='Range 2')

l = widgets.jslink((range1, 'value'), (range2, 'value'))
display(caption, range1, range2)

# NO LAG VERSION
caption = widgets.Label(value = 'Changes in source_range values are reflected in target_range1')

source_range = widgets.IntSlider(description='Source range')
target_range1 = widgets.IntSlider(description='Target range ')

dl = widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))
display(caption, source_range, target_range1)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button can be used to register function to be called when the button is clicked. The doc string of the on_click can be seen below.
Can you write Python code for it?

import ipywidgets as widgets
print(widgets.Button.on_click.__doc__)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/3 - Widget Events.ipynb".
The first task is:
Traitlet events
Widget properties are IPython traitlets and traitlets are eventful. To handle changes, the on_trait_change method of the widget can be used to register a callback.  The doc string for on_trait_change can be seen below.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Boolean widgets
There are three widgets that are designed to display a boolean value.
ToggleButton
Can you write Python code for it?

widgets.ToggleButton(
    description='Click me',
    value=False,
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
FloatProgress
Can you write Python code for it?

widgets.FloatProgress(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Loading:',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
FloatText
Can you write Python code for it?

widgets.FloatText(
    value=7.5,
    description='Any:',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Latex
Can you write Python code for it?

widgets.Latex(
    value="$$\\frac{n!}{k!(n-k)!}$$",
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Select
Can you write Python code for it?

widgets.Select(
    description='OS:',
    options=['Linux', 'Windows', 'OSX'],
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
SelectMultiple
Multiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys.
Can you write Python code for it?

w = widgets.SelectMultiple(
    description="Fruits",
    options=['Apples', 'Oranges', 'Pears'])

display(w)

w.value


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Selection widgets
There are four widgets that can be used to display single selection lists, and one that can be used to display multiple selection lists. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list. You can also specify the enumeration as a dictionary, in which case the keys will be used as the item displayed in the list and the corresponding value will be returned when an item is selected.
Dropdown
Can you write Python code for it?

from IPython.display import display

w = widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Number:',
)
display(w)

# Show value
w.value


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Sliders can also be displayed vertically.
Can you write Python code for it?

widgets.FloatSlider(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Test',
    orientation='vertical',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
String widgets
There are 4 widgets that can be used to display a string value. Of those, the Text and Textarea widgets accept input. The Latex and HTML widgets display the string as either Latex or HTML respectively, but do not accept input.
Text
Can you write Python code for it?

widgets.Text(
    description='String:',
    value='Hello World',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Textarea
Can you write Python code for it?

widgets.Textarea(
    description='String:',
    value='Hello World',
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
The following is also valid:
Can you write Python code for it?

w = widgets.Dropdown(
    options={'One': 1, 'Two': 2, 'Three': 3},
    value=2,
    description='Number:')

display(w)

w.value


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
ToggleButtons
Can you write Python code for it?

widgets.ToggleButtons(
    description='Speed:',
    options=['Slow', 'Regular', 'Fast'],
)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/4 - Widget List.ipynb".
The first task is:
Valid
The valid widget provides a read-only indicator.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Alignment
Most widgets have a description attribute, which allows a label for the widget to be defined.
The label of the widget has a fixed minimum width.
The text of the label is always right aligned and the widget is left aligned:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Another example
In the example below, a form is rendered, which conditionally displays widgets depending on the state of other widgets. Try toggling the student check-box.
Can you write Python code for it?

form = widgets.VBox()
first = widgets.Text(description="First:")
last = widgets.Text(description="Last:")

student = widgets.Checkbox(description="Student:", value=False)
school_info = widgets.VBox(visible=False, children=[
    widgets.Text(description="School:"),
    widgets.IntText(description="Grade:", min=0, max=12)
    ])

pet = widgets.Text(description="Pet:")
form.children = [first, last, student, school_info, pet]
display(form)

def on_student_toggle(name, value):
    if value:
        school_info.visible = True
    else:
        school_info.visible = False
student.on_trait_change(on_student_toggle, 'value')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Basic styling
The widgets distributed with IPython can be styled by setting the following traits:

width
height
background_color
border_color
border_width
border_style
font_style
font_weight
font_size
font_family

The example below shows how a Button widget can be styled:
Can you write Python code for it?

button = widgets.Button(
    description='Hello World!',
    width=100, # Integers are interpreted as pixel measurements.
    height='2em', # em is valid HTML unit of measurement.
    color='lime', # Colors can be set by name,
    background_color='#0022FF', # and also by color code.
    border_color='cyan')
display(button)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Flex boxes
Widgets can be aligned using the FlexBox, HBox, and VBox widgets.
Application to widgets
Widgets display vertically by default:
Can you write Python code for it?

buttons = [widgets.Button(description=str(i)) for i in range(3)]
display(*buttons)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
If a description is not set for the widget, the label is not displayed:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Parent/child relationships
To display widget A inside widget B, widget A must be a child of widget B. Widgets that can contain other widgets have a children attribute. This attribute can be set via a keyword argument in the widget's constructor or after construction. Calling display on an object with children automatically displays the children.
Can you write Python code for it?

from IPython.display import display

float_range = widgets.FloatSlider()
string = widgets.Text(value='hi')
container = widgets.Box(children=[float_range, string])

container.border_color = 'red'
container.border_style = 'dotted'
container.border_width = 3
display(container) # Displays the `container` and all of it's children.


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
TabWidget
Can you write Python code for it?

name = widgets.Text(description='Name:', padding=4)
color = widgets.Dropdown(description='Color:', padding=4, options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
page1 = widgets.Box(children=[name, color], padding=4)

age = widgets.IntSlider(description='Age:', padding=4, min=0, max=120, value=50)
gender = widgets.RadioButtons(description='Gender:', padding=4, options=['male', 'female'])
page2 = widgets.Box(children=[age, gender], padding=4)

tabs = widgets.Tab(children=[page1, page2])
display(tabs)

tabs.set_title(0, 'Name')
tabs.set_title(1, 'Details')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Using hbox
To make widgets display horizontally, they can be children of an HBox widget.
Can you write Python code for it?

container = widgets.HBox(children=buttons)
display(container)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/5 - Widget Styling.ipynb".
The first task is:
Visibility
The visible property of widgets can be used to hide or show widgets that have already been displayed (as seen below). The visible property can be:
* True - the widget is displayed
* False - the widget is hidden, and the empty space where the widget would be is collapsed
* None - the widget is hidden, and the empty space where the widget would be is shown
Can you write Python code for it?

w1 = widgets.Latex(value="First line")
w2 = widgets.Latex(value="Second line")
w3 = widgets.Latex(value="Third line")
display(w1, w2, w3)

w2.visible=None

w2.visible=False

w2.visible=True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/6 - Custom Widget.ipynb".
The first task is:
After interacting with the system, we can take the result and perform further computations. In this case, we compute the average positions in $x$, $y$ and $z$.
Can you write Python code for it?

xyz_avg = x_t.mean(axis=1)

xyz_avg.shape


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/6 - Custom Widget.ipynb".
The first task is:
Computing the trajectories and plotting the result
We define a function that can integrate the differential equations numerically and then plot the solutions. This function has arguments that control the parameters of the differential equation ($\sigma$, $\beta$, $\rho$), the numerical integration (N, max_time) and the visualization (angle).
Can you write Python code for it?

def solve_lorenz(N=10, angle=0.0, max_time=4.0, sigma=10.0, beta=8./3, rho=28.0):

    fig = plt.figure();
    ax = fig.add_axes([0, 0, 1, 1], projection='3d');
    ax.axis('off')

    # prepare the axes limits
    ax.set_xlim((-25, 25))
    ax.set_ylim((-35, 35))
    ax.set_zlim((5, 55))

    def lorenz_deriv(x_y_z, t0, sigma=sigma, beta=beta, rho=rho):
        """Compute the time-derivative of a Lorenz system."""
        x, y, z = x_y_z
        return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]

    # Choose random starting points, uniformly distributed from -15 to 15
    np.random.seed(1)
    x0 = -15 + 30 * np.random.random((N, 3))

    # Solve for the trajectories
    t = np.linspace(0, max_time, int(250*max_time))
    x_t = np.asarray([integrate.odeint(lorenz_deriv, x0i, t)
                      for x0i in x0])

    # choose a different color for each trajectory
    colors = plt.cm.jet(np.linspace(0, 1, N));

    for i in range(N):
        x, y, z = x_t[i,:,:].T
        lines = ax.plot(x, y, z, '-', c=colors[i])
        _ = plt.setp(lines, linewidth=2);

    ax.view_init(30, angle)
    _ = plt.show();

    return t, x_t


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/6 - Custom Widget.ipynb".
The first task is:
Let's call the function once to view the solutions. For this set of parameters, we see the trajectories swirling around two points, called attractors.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/GUI/6 - Custom Widget.ipynb".
The first task is:
The object returned by interactive is a Widget object and it has attributes that contain the current result and arguments:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators Homework - Solution.ipynb".
The first task is:
Problem 2
Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example:
Can you write Python code for it?

import random

random.randint(1,10)

def rand_num(low,high,n):

    for i in range(n):
        yield random.randint(low, high)

for num in rand_num(1,10,12):
    print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators Homework - Solution.ipynb".
The first task is:
Problem 4
Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
If the output has the potential of taking up a large amount of memory and you only intend to iterate through it, you would want to use a generator. (Multiple answers are acceptable here!)
Extra Credit!
Can you explain what bonus is in the code below? (Note: We never covered this in lecture!)
Can you write Python code for it?

my_list = [1,2,3,4,5]

gencomp = (item for item in my_list if item > 3)

for item in gencomp:
    print item


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators Homework.ipynb".
The first task is:
Problem 2
Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example:
Can you write Python code for it?

import random

random.randint(1,10)

def rand_num(low,high,n):
    pass

for num in rand_num(1,10,12):
    print num


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators Homework.ipynb".
The first task is:
Problem 3
Use the iter() function to convert the string below
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators Homework.ipynb".
The first task is:
Problem 4
Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
Extra Credit!
Can you explain what gencomp is in the code below? (Note: We never covered this in lecture! You will have to do some googling/Stack Overflowing!)
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators.ipynb".
The first task is:
After yielding all the values next() caused a StopIteration error. What this error informs us of is that all the values have been yielded.
You might be wondering that why don’t we get this error while using a for loop? The for loop automatically catches this error and stops calling next.
Lets go ahead and check out how to use iter(). You remember that strings are iterables:
Can you write Python code for it?

s = 'hello'

#Iterate over string
for let in s:
    print let


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators.ipynb".
The first task is:
Interesting, this means that a string object supports iteration, but we can not directly iterate over it as we could with a generator function. The iter() function allows us to do just that!
Can you write Python code for it?

s_iter = iter(s)

next(s_iter)

next(s_iter)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Iterators and Generators.ipynb".
The first task is:
Notice that if we call some huge value of n (like 100000) the second function will have to keep track of every single result, when in our case we actually only care about the previous result to generate the next one!
next() and iter() built-in functions
A key to fully understanding generators is the next function() and the iter() function.
The next function allows us to access the next element in a sequence. Lets check it out:
Can you write Python code for it?

def simple_gen():
    for x in range(3):
        yield x

# Assign simple_gen
g = simple_gen()

print next(g)

print next(g)

print next(g)

print next(g)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/List Comprehensions.ipynb".
The first task is:
Example 3
Lets see how to add in if statements:
Can you write Python code for it?

# Check for even numbers in a range
lst = [x for x in range(11) if x % 2 == 0]

lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/List Comprehensions.ipynb".
The first task is:
Example 5
We can also perform nested list comprehensions, for example:
Can you write Python code for it?

lst = [ x**2 for x in [x**2 for x in range(11)]]
lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/List Comprehensions.ipynb".
The first task is:
This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example: x^2 : x in { 0,1,2...10}
Lets see a few more example of list comprehensions in Python:
Example 2
Can you write Python code for it?

# Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]

lst


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Basic List Methods
If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
Let's go ahead and explore some more special methods for lists:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Indexing and Slicing
Indexing and slicing works just like in strings. Let's make a new list to remind ourselves of how this works:
Can you write Python code for it?

my_list = ['one','two','three',4,5]

# Grab element at index 0
my_list[0]

# Grab index 1 and everything past it
my_list[1:]

# Grab everything UP TO index 3
my_list[:3]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
It should also be noted that lists indexing will return an error if there is no element at that index. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Just like strings, the len() function will tell you how many items are in the sequence of the list.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
List Comprehensions
Python has an advanced feature called list comprehensions. They allow for quick construction of lists. To fully understand list comprehensions we need to understand for loops. So don't worry if you don't completely understand this section, and feel free to just skip it since we will return to this topic later.
But in case you want to know now, here are a few examples!
Can you write Python code for it?

# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]

first_col


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Nesting Lists
A great feature of of Python data structures is that they support nesting. This means we can have data structures within data structures. For example: A list inside a list.
Let's see how this works!
Can you write Python code for it?

# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]

# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]

# Show
matrix


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Note: This doesn't actually change the original list!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Now we can again use indexing to grab elements, but now there are two levels for the index. The items in the matrix object, and then the items inside that list!
Can you write Python code for it?

# Grab first item in matrix object
matrix[0]

# Grab first item of the first item in the matrix object
matrix[0][0]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
Use pop to "pop off" an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let's see an example:
Can you write Python code for it?

# Pop off the 0 indexed item
l.pop(0)

# Show
l

# Assign the popped element, remember default popped index is -1
popped_item = l.pop()

popped_item

# Show remaining list
l


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
We can also use + to concatenate lists, just like we did for strings.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
We can also use the * for a duplication method similar to strings:
Can you write Python code for it?

# Make the list double
my_list * 2

# Again doubling not permanent
my_list


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
We can use the sort method and the reverse methods to also effect your lists:
Can you write Python code for it?

new_list = ['a','e','x','b','c']

#Show
new_list

# Use reverse to reverse order (this is permanent!)
new_list.reverse()

new_list

# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()

new_list


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Lists.ipynb".
The first task is:
We just created a list of integers, but lists can actually hold different object types. For example:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Map.ipynb".
The first task is:
Great! We got the same result! Using map is much more commonly used with lambda expressions since the entire purpose of map() is to save effort on having to create manual for loops.
map() can be applied to more than one iterable. The iterables have to have the same length.
For instance, if we are working with two lists-map() will apply its lambda function to the elements of the argument lists, i.e. it first applies to the elements with the 0th index, then to the elements with the 1st index until the n-th index is reached.
For example lets map a lambda expression to two lists:
Can you write Python code for it?

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]

map(lambda x,y:x+y,a,b)

# Now all three lists
map(lambda x,y,z:x+y+z, a,b,c)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Map.ipynb".
The first task is:
In the example above we haven't used a lambda expression. By using lambda, we wouldn't have had to define and name the functions fahrenheit() and celsius().
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Map.ipynb".
The first task is:
Now lets see map() in action:
Can you write Python code for it?

F_temps = map(fahrenheit, temp)

#Show
F_temps

# Convert back
map(celsius, F_temps)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1 - Advanced Solution.ipynb".
The first task is:
Define function to check if the board is already full in case of a tie. (This is straightforward with our board stored as a list)
Just remember index 0 is always empty.
Can you write Python code for it?

def full_board_check(board):
    ''' Function to check if any remaining blanks are in the board '''
    if " " in board[1:]:
        return False
    else:
        return True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1 - Advanced Solution.ipynb".
The first task is:
Let's play!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1 - Advanced Solution.ipynb".
The first task is:
Next make a function that will reset the board, in this case we'll store values as a list.
Can you write Python code for it?

# Note: Game will ignore the 0 index
def reset_board():
    global board,game_state
    board = [' '] * 10
    game_state = True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1 - Advanced Solution.ipynb".
The first task is:
Now create a function to display the board, I'll use the num pad as the board reference.
Note: Should probably just make board and player classes later....
Can you write Python code for it?

def display_board():
    ''' This function prints out the board so the numpad can be used as a reference '''
    # Clear current cell output
    clear_output()
    # Print board
    print "  "+board[7]+" |"+board[8]+" | "+board[9]+" "
    print "------------"
    print "  "+board[4]+" |"+board[5]+" | "+board[6]+" "
    print "------------"
    print "  "+board[1]+" |"+board[2]+" | "+board[3]+" "


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1 - Advanced Solution.ipynb".
The first task is:
Now have a function that takes in the player's choice (via the ask_player function) then returns the game_state.
Can you write Python code for it?

def player_choice(mark):
    global board,game_state,announce
    #Set game blank game announcement
    announce = ''
    #Get Player Input
    mark = str(mark)
    # Validate input
    ask_player(mark)

    #Check for player win
    if win_check(board,mark):
        clear_output()
        display_board()
        announce = mark +" wins! Congratulations"
        game_state = False

    #Show board
    clear_output()
    display_board()

    #Check for a tie
    if full_board_check(board):
        announce = "Tie!"
        game_state = False

    return game_state,announce


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.
Can you write Python code for it?

from IPython.display import clear_output
def display_board(board):

    clear_output()
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using while loops to continually ask until you get a correct answer.
Can you write Python code for it?

def player_input():

    marker = ''
    while not (marker == 'X' or marker == 'O'):
        marker = raw_input('Player 1: Do you want to be X or O?').upper()

    if marker == 'X':
        return ('X', 'O')
    else:
        return ('O', 'X')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.
Can you write Python code for it?

import random
def choose_first():
    if random.randint(0, 1) == 0:
        return 'Player 2'
    else:
        return 'Player 1'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.
Can you write Python code for it?

def full_board_check(board):
    for i in range(1,10):
        if space_check(board, i):
            return False
    return True


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. If it is, then return the position for later use.
Can you write Python code for it?

def player_choice(board):
    # Using strings because of raw_input
    position = ' '
    while position not in '1 2 3 4 5 6 7 8 9'.split() or not space_check(board, int(position)):

        position = raw_input('Choose your next position: (1-9) ')
    return int(position)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Complete Walkthrough Solution.ipynb".
The first task is:
Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.
Can you write Python code for it?

def replay():

    return raw_input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!
Can you write Python code for it?

print('Welcome to Tic Tac Toe!')

#while True:
    # Set the game up here
    #pass

    #while game_on:
        #Player 1 Turn

        # Player2's turn.

            #pass

    #if not replay():
        #break


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.
Can you write Python code for it?

from IPython.display import clear_output
def display_board(board):

    pass


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using while loops to continually ask until you get a correct answer.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.
Can you write Python code for it?

import random
def choose_first():
    pass


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. If it is, then return the position for later use.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 1- Walkthrough Steps Workbook.ipynb".
The first task is:
Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Function to read user input
Can you write Python code for it?

def player_input():
    ''' Read user input, lower case it just to be safe'''
    plin = raw_input().lower()

    if plin == 'h':
        hit()
    elif plin == 's':
        stand()
    elif plin == 'd':
        deal_cards()
    elif plin == 'q':
        game_exit()
    else:
        print "Invalid Input...Enter h, s, d, or q: "
        player_input()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Next I'll make a deck class
Can you write Python code for it?

class Deck:

    def __init__(self):
        ''' Create a deck in order '''
        self.deck = []
        for suit in suits:
            for rank in ranking:
                self.deck.append(Card(suit,rank))

    def shuffle(self):
        ''' Shuffle the deck, python actually already has a shuffle method in its random lib '''
        random.shuffle(self.deck)

    def deal(self):
        ''' Grab the first item in the deck '''
        single_card = self.deck.pop()
        return single_card

    def __str__(self):
        deck_comp = ""
        for card in self.cards:
            deck_comp += " " + deck_comp.__str__()

        return "The deck has" + deck_comp


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Now I'll make a card class, it will have some basic ID functions, and then some functions to grab the suit and rank of the card.
Can you write Python code for it?

# Create a card class
class Card:

    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return self.suit + self.rank

    def grab_suit(self):
        return self.suit

    def grab_rank(self):
        return self.rank

    def draw(self):
        print (self.suit + self.rank)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Now make the stand function
Can you write Python code for it?

def stand():
    global playing,chip_pool,deck,player_hand,dealer_hand,result,bet
    ''' This function will now play the dealers hand, since stand was chosen '''

    if playing == False:
        if player_hand.calc_val() > 0:
            result = "Sorry, you can't stand!"

    # Now go through all the other possible options
    else:

        # Soft 17 rule
        while dealer_hand.calc_val() < 17:
            dealer_hand.card_add(deck.deal())

        # Dealer Busts
        if dealer_hand.calc_val() > 21:
            result = 'Dealer busts! You win!' + restart_phrase
            chip_pool += bet
            playing = False

        #Player has better hand than dealer
        elif dealer_hand.calc_val() < player_hand.calc_val():
            result = 'You beat the dealer, you win!' + restart_phrase
            chip_pool += bet
            playing = False

        # Push
        elif dealer_hand.calc_val() == player_hand.calc_val():
            result = 'Tied up, push!' + restart_phrase
            playing = False

        # Dealer beats player
        else:
            result = 'Dealer Wins!' + restart_phrase
            chip_pool -= bet
            playing = False
    game_step()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Now that the classes are done, time for the cool part, creating the actual game!
First off, making a bet. Need to check if the bet amount is within the integer.
Can you write Python code for it?

# First Bet
def make_bet():
    ''' Ask the player for the bet amount and '''

    global bet
    bet = 0

    print ' What amount of chips would you like to bet? (Enter whole integer please) '

    # While loop to keep asking for the bet
    while bet == 0:
        bet_comp = raw_input() # Use bet_comp as a checker
        bet_comp = int(bet_comp)
        # Check to make sure the bet is within the remaining amount of chips left.
        if bet_comp >= 1 and bet_comp <= chip_pool:
            bet = bet_comp
        else:
            print "Invalid bet, you only have " + str(chip_pool) + " remaining"


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Milestone Project 2 Solution.ipynb".
The first task is:
Now to play the game!
Can you write Python code for it?

'''The following code will initiate the game! (Note: Need to Run all Cells)'''

# Create a Deck
deck = Deck()
#Shuffle it
deck.shuffle()
# Create player and dealer hands
player_hand = Hand()
dealer_hand = Hand()
#Print the intro
intro()
# Deal out the cards and start the game!
deal_cards()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Nested Statements and Scope.ipynb".
The first task is:
Built-in
These are the built-in function names in Python (don't overwrite these!)
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Nested Statements and Scope.ipynb".
The first task is:
Enclosing function locals
This occurs when we have a function inside a function (nested functions)
Can you write Python code for it?

name = 'This is a global name'

def greet():
    # Enclosing function
    name = 'Sammy'

    def hello():
        print 'Hello '+name

    hello()

greet()


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Nested Statements and Scope.ipynb".
The first task is:
Local Variables
When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.
Example:
Can you write Python code for it?

x = 50

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

func(x)
print 'x is still', x


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Nested Statements and Scope.ipynb".
The first task is:
The first time that we print the value of the name x with the first line in the function’s body, Python uses the value of the parameter declared in the main block, above the function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected.
With the last print statement, we display the value of x as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.
The global statement
If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.
You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block.
Example:
Can you write Python code for it?

x = 50

def func():
    global x
    print 'This function is now using the global x!'
    print 'Because of global x is: ', x
    x = 2
    print 'Ran func(), changed global x to', x

print 'Before calling func(), x is: ', x
func()
print 'Value of x (outside of func()) is: ', x


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Nested Statements and Scope.ipynb".
The first task is:
What do you imagine the output of printer() is? 25 or 50? What is the output of print x? 25 or 50?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
Python 3 Alert!
Whoa! What just happened? Last time I checked, 3 divided by 2 is equal 1.5 not 1!
The reason we get this result is because we are using Python 2. In Python 2, the / symbol performs what is known as "classic" division, this means that the decimal points are truncated (cut off). In Python 3 however, a single / performs "true" division. So you would get 1.5 if you had inputed 3/2 in Python 3.
So what do we do if we are using Python 2 to avoid this?
There are two options:
Specify one of the numbers to be a float:
Can you write Python code for it?

# Specifying one of the numbers as a float
3.0/2

# Works for either number
3/2.0


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
Now if I call a in my Python script, Python will treat it as the number 5.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
Variable Assignments
Now that we've seen how to use numbers in Python as a calculator let's see how we can assign names and create variables.
We use a single equals sign to assign labels to variables. Let's see a few examples of how we can do this.
Can you write Python code for it?

# Let's create an object called "a" and assign it the number 5
a = 5


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
We could also "cast" the type using a function that basically turns integers into floats. This function, unsurprisingly, is called float().
Can you write Python code for it?

# We can use this float() function to cast integers as floats:
float(3)/2


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
What happens on reassignment? Will Python let us write it over?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
When you import division from the future you won't need to worry about classic division occurring anymore anywhere in your code!
Arithmetic continued
Can you write Python code for it?

# Powers
2**3

# Can also do roots this way
4**0.5

# Order of Operations followed in Python
2 + 10 * 10 + 3

# Can use parenthesis to specify orders
(2+10) * (10+3)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Numbers.ipynb".
The first task is:
Yes! Python allows you to write over assigned variable names. We can also use the variables themselves when doing the reassignment. Here is an example of what I mean:
Can you write Python code for it?

# Check
a

# Use A to redefine A
a = a + a

# Check
a


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Object Oriented Programming.ipynb".
The first task is:
In this example, we have two classes: Animal and Dog. The Animal is the base class, the Dog is the derived class.
The derived class inherits the functionality of the base class.

It is shown by the eat() method.

The derived class modifies existing behavior of the base class.

shown by the whoAmI() method.

Finally, the derived class extends the functionality of the base class, by defining a new bark() method.
Special Methods
Finally lets go over special methods. Classes in Python can implement certain operations with special method names. These methods are not actually called directly but by Python specific language syntax. For example Lets create a Book class:
Can you write Python code for it?

class Book(object):
    def __init__(self, title, author, pages):
        print "A book is created"
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return "Title:%s , author:%s, pages:%s " %(self.title, self.author, self.pages)

    def __len__(self):
        return self.pages

    def __del__(self):
        print "A book is destroyed"

book = Book("Python Rocks!", "Jose Portilla", 159)

#Special Methods
print book
print len(book)
del book


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Object Oriented Programming.ipynb".
The first task is:
Lets break down what we have above.The special method
__init__()

is called automatically right after the object has been created:
def __init__(self, breed):

Each attribute in a class definition begins with a reference to the instance object. It is by convention named self. The breed is the argument. The value is passed during the class instantiation.
 self.breed = breed

Now we have created two instances of the Dog class. With two breed types, we can then access these attributes like this:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Object Oriented Programming.ipynb".
The first task is:
Remember how we could call methods on a list?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Object Oriented Programming.ipynb".
The first task is:
So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.
class
The user defined objects are created using the class keyword. The class is a blueprint that defines a nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class. For example, above we created the object 'l' which was an instance of a list object.
Let see how we can use class:
Can you write Python code for it?

# Create a new object type called Sample
class Sample(object):
    pass

# Instance of Sample
x = Sample()

print type(x)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Answer: Because Python 2 performs classic division for integers. Use floats to perform true division. For example:
2.0/3
Answer these 3 questions without typing code. Then type code to check your answer.
What is the value of the expression 4 * (6 + 5)

What is the value of the expression 4 * 6 + 5

What is the value of the expression 4 + 6 * 5
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Booleans
For the following quiz questions, we will get a preview of comparison operators:

Operator	Description	Example

==
If the values of two operands are equal, then the condition becomes true.
 (a == b) is not true.

!=
If values of two operands are not equal, then condition becomes true.

<>
If values of two operands are not equal, then condition becomes true.
 (a <> b) is true. This is similar to != operator.

>
If the value of left operand is greater than the value of right operand, then condition becomes true.
 (a > b) is not true.

<
If the value of left operand is less than the value of right operand, then condition becomes true.
 (a < b) is true.

>=
If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
 (a >= b) is not true.

<=
If the value of left operand is less than or equal to the value of right operand, then condition becomes true.
 (a <= b) is true.

What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)
Can you write Python code for it?

# Answer before running cell
2 > 3

# Answer before running cell
3 <= 2

# Answer before running cell
3 == 2.0

# Answer before running cell
3.0 == 3

# Answer before running cell
4**0.5 != 2


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Can you sort a dictionary? Why or why not?
Answer: No! Because normal dictionaries are mappings not a sequence.
Tuples
What is the major difference between tuples and lists?
Tuples are immutable!
How do you create a tuple?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Dictionaries
Using keys and indexing, grab the 'hello' from the following dictionaries:
Can you write Python code for it?

d = {'simple_key':'hello'}
# Grab 'hello'

d['simple_key']

d = {'k1':{'k2':'hello'}}
# Grab 'hello'

d['k1']['k2']

# Getting a little tricker
d = {'k1':[{'nest_key':['this is deep',['hello']]}]}

# This was harder than I expected...
d['k1'][0]['nest_key'][1][0]

# This will be hard and annoying!
d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}

# Phew
d['k1'][2]['k2'][1]['tough'][2][0]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Explain what the cell below will produce and why. Can you change it so the answer is correct?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Given the string hello, give two methods of producing the letter 'o' using indexing.
Can you write Python code for it?

s ='hello'

# Print out the

s[-1]

s[4]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Lists
Build this list [0,0,0] two separate ways.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Sets
What is unique about a set?
Answer: They don't allow for duplicate items!
Use a set to find the unique values of the list below:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Sort the list below:
Can you write Python code for it?

l = [5,3,4,6,1]

#Method 1
sorted(l)

#Method 2
l.sort()
l


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
Strings
Given the string 'hello' give an index command that returns 'e'. Use the code below:
Can you write Python code for it?

s = 'hello'
# Print out 'e' using indexing
s[1]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test-Solution.ipynb".
The first task is:
What is the type of the result of the expression 3 + 1.5 + 4?
Answer: Floating Point Number
What would you use to find a number’s square root, as well as its square?
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Answer these 3 questions without typing code. Then type code to check your answer.
What is the value of the expression 4 * (6 + 5)

What is the value of the expression 4 * 6 + 5

What is the value of the expression 4 + 6 * 5

What is the type of the result of the expression 3 + 1.5 + 4?
What would you use to find a number’s square root, as well as its square?
Strings
Given the string 'hello' give an index command that returns 'e'. Use the code below:
Can you write Python code for it?

s = 'hello'
# Print out 'e' using indexing

# Code here


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Booleans
For the following quiz questions, we will get a preview of comparison operators:

Operator	Description	Example

==
If the values of two operands are equal, then the condition becomes true.
 (a == b) is not true.

!=
If values of two operands are not equal, then condition becomes true.

<>
If values of two operands are not equal, then condition becomes true.
 (a <> b) is true. This is similar to != operator.

>
If the value of left operand is greater than the value of right operand, then condition becomes true.
 (a > b) is not true.

<
If the value of left operand is less than the value of right operand, then condition becomes true.
 (a < b) is true.

>=
If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
 (a >= b) is not true.

<=
If the value of left operand is less than or equal to the value of right operand, then condition becomes true.
 (a <= b) is true.

What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Can you sort a dictionary? Why or why not?
Tuples
What is the major difference between tuples and lists?
How do you create a tuple?
Sets
What is unique about a set?
Use a set to find the unique values of the list below:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Dictionaries
Using keys and indexing, grab the 'hello' from the following dictionaries:
Can you write Python code for it?

d = {'simple_key':'hello'}
# Grab 'hello'

d = {'k1':{'k2':'hello'}}
# Grab 'hello'

# Getting a little tricker
d = {'k1':[{'nest_key':['this is deep',['hello']]}]}

#Grab hello

# This will be hard and annoying!
d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Lists
Build this list [0,0,0] two separate ways.
Reassign 'hello' in this nested list to say 'goodbye' item in this list:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Reverse the string 'hello' using indexing:
Can you write Python code for it?

s ='hello'

# Reverse the string using indexing

# Code here


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Objects and Data Structures Assessment Test.ipynb".
The first task is:
Sort the list below:
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Print Formatting.ipynb".
The first task is:
Conversion Format methods.
It should be noted that two methods %s and %r actually convert any python object to a string using two separate methods: str() and repr(). We will learn more about these functions later on in the course, but you should note you can actually pass almost any Python object with these two methods and it will work:
Can you write Python code for it?

print 'Here is a number: %s. Here is a string: %s' %(123.1,'hi')

print 'Here is a number: %r. Here is a string: %r' %(123.1,'hi')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Print Formatting.ipynb".
The first task is:
Strings
You can use the %s to format strings into your print statements.
Can you write Python code for it?

s = 'STRING'
print 'Place another string with a mod and s: %s' %(s)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Statements Assessment Test.ipynb".
The first task is:
Go through the string below and if the length of a word is even print "even!"
Can you write Python code for it?

st = 'Print every word in this sentence that has an even number of letters'

#Code in this cell


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Statements Assessment Test.ipynb".
The first task is:
Use List Comprehension to create a list of the first letters of every word in the string below:
Can you write Python code for it?

st = 'Create a list of the first letters of every word in this string'

#Code in this cell


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Statements Assessment Test.ipynb".
The first task is:
Use List comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Statements Assessment Test.ipynb".
The first task is:
Use range() to print all the even numbers from 0 to 10.
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
Basic Built-in String methods
Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.
We call methods with a period and then the method name. Methods are in the form:
object.method(parameters)
Where parameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. Later on we will be creating our own objects and functions!
Here are some examples of built-in methods in strings:
Can you write Python code for it?

s

# Upper Case a string
s.upper()

# Lower case
s.lower()

# Split a string by blank space (this is the default)
s.split()

# Split by a specific element (doesn't include the element that was split on)
s.split('W')


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
Let's start indexing!
Can you write Python code for it?

# Show first element (in this case a letter)
s[0]

s[1]

s[2]


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
Notice how the error tells us directly what we can't do, change the item assignment!
Something we can do is concatenate strings!
Can you write Python code for it?

s

# Concatenate strings!
s + ' concatenate me!'

# We can reassign s completely though!
s = s + ' concatenate me!'

print(s)

s


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
Now let's learn about printing strings!
Printing a String
Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function.
Can you write Python code for it?

# We can simply declare a string
'Hello World'

# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
String Basics
We can also use a function called len() to check the length of a string!
Can you write Python code for it?


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
String Indexing
We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let's learn how this works.
In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let's create a new object called s and the walk through a few examples of indexing.
Can you write Python code for it?

# Assign s as a string
s = 'Hello World'

#Check
s

# Print the object
print(s)


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
String Properties
Its important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. For example:
Can you write Python code for it?

s

# Let's try to change the first letter to 'x'
s[0] = 'x'


I am working on the file "PythonBootCamp/Complete-Python-Bootcamp-master/Strings.ipynb".
The first task is:
We can use a : to perform slicing which grabs everything up to a designated point. For example:
Can you write Python code for it?

# Grab everything past the first term all the way to the length of s which is len(s)
s[1:]

# Note that there is no change to the original s
s

# Grab everything UP TO the 3rd index
s[:3]


I am working on the file "PythonInstallation.ipynb".
The first task is:
Anaconda Installation
includes: python, ipython, spyder, jupyter, and more...
Author: Barron Henderson
Better instructions are elsewhere

These were written for distribution for a specific workshop
These might be out of date
Anaconda website (https://www.continuum.io/downloads) may be more throrough
If you're still reading, go ahead and use these.

Windows Installation
How-to

Select an installer from below
Download the installer
unzip first, only if necessary
Double click installer
Follow instructions to install
if you have admin rights, for system
if you don't, just your user - install directly in user directory.

Windows not zipped

64-bit: http://repo.continuum.io/archive/Anaconda3-4.0.0-Windows-x86_64.exe
32-bit: http://repo.continuum.io/archive/Anaconda3-4.0.0-Windows-x86.exe
64-bit-zipped: https://repo.continuum.io/archive/.winzip/Anaconda3-4.0.0-Windows-x86_64.zip
32-bit-zipped: https://repo.continuum.io/archive/.winzip/Anaconda3-4.0.0-Windows-x86.zip

OS X graphical

Download http://repo.continuum.io/archive/Anaconda3-4.0.0-MacOSX-x86_64.pkg
Double click
Follow instructions to install
if you have admin rights, for system
if you don't, just your user

OS X Command line

Download: http://repo.continuum.io/archive/Anaconda3-4.0.0-MacOSX-x86_64.sh
Open a terminal (command+space, type terminal, enter)
cd ~/Downloads
bash Anaconda3-4.0.0-MacOSX-x86_64.sh
Follow instructions to install
if you have admin rights, for system
if you don't, just your user
Can you write Python code for it?

%%bash
cd ~/Downloads
curl -LO http://repo.continuum.io/archive/Anaconda3-4.0.0-MacOSX-x86_64.sh
bash Anaconda3-4.0.0-MacOSX-x86_64.sh


I am working on the file "PythonInstallation.ipynb".
The first task is:
Extra Libraries
Most libraries we use, come with Anaconda. Some, however, need a little version syncronizing.
Windows

Download shapely for later http://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely
Download basemap for later http://www.lfd.uci.edu/~gohlke/pythonlibs/#basemap
Can you write Python code for it?


I am working on the file "PythonInstallation.ipynb".
The first task is:
Install PNC Library
PseudoNetCDF is an important library for processing Atmospheric data formats (bpch, uamiv, etc).

Visit site http://github.com/barronh/pseudonetcdf
How do you install it?
To get the latest version, add "--upgrade"

ANSWER HIDDEN
<div class="answers">
```
!pip install http://github.com/barronh/pseudonetcdf/archive/master.zip
```
</div>

Run pncdump.py
Just as a test.
1. Run with help option
2. Run with dummy path
Can you write Python code for it?


I am working on the file "PythonInstallation.ipynb".
The first task is:
Mac
Can you write Python code for it?


I am working on the file "PythonInstallation.ipynb".
The first task is:
Windows file association

Do not make your own file associations.
If you do, you may need to delete it (http://websistent.com/delete-file-association-windows-7/)
If that still doesn't work, open a dos prompt.
Can you write Python code for it?

!assoc .py=Python.File
!ftype Python.File="C:\Users\barronh\Anaconda3\python.exe" "%1" %*


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:

Operators and Flow control
back
Operators
Arithmetic Operators

Used for mathematical operations
plus (+), minus (-), multiply (), divide (/), modulus (%), raise (*)

Comparison Operators

Used to compare two values
Returns True or False as result
Greater than (>), lesser than (<), equal (==), not equal (!=)
Attention: = is an assignment, == is the comparison operator

Logical Operators

Used to connect logical statements
and, or and not

Flow Control
for Loop

the for loop is used to iterate over a sequence
python
for x in y:
    counter = counter +1

Loop continues until it reaches last item in y

Example: Sum of numbers
```python
        # List of numbers
        numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
    sum = sum + val

```

if/elif/else

These are used to make decisions in a program
python
        if x == 2:  # expression
            print(my_string)  # statement
expression is evaluated, if True, statements will be executed
python
        if x == 2:  # expression
            print(my_string)  # body of if
        else:
            print(your_string)  # body of else
expression is evaluated, if True, statement in body of if will be executed, otherwise statement in body of else will be executed
python
        if x == 2:  # 1st expression
            print(my_string)  # body of if
        elif x == 3:  # 2nd expression
            print(our_string)  # body of elif
        else:
            print(your_string)  # body of else
elif is short for else if
1st expression is evaluated, if True, statement in body of if will be executed, otherwise 2nd expression will be checked and so on...

while Loop

while iterates over a block of code, as long as a statement is True

Is used when the number of times the loop has to be executed is not known beforehand (compare: for loop)
python
        while x < 2:  # expression
            print(our_string)

expression is checked before...
Can you write Python code for it?


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:
Boolean

A Boolean can only hold the values True or False
Can be compared by logical operators

Mutable vs. Immutable
Can you write Python code for it?

### example immutable
x = 10
y = x
x = x + 1
print('y: ',y)

### example mutable
x_l = ['10']
y_l = x_l
x_l.append('11')
print('y_l: ', y_l)


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:
Numerical Data Types

Python has integers, floating point numbers and complex numbers
Python assigns a data type to each variable $\rightarrow$ 1 is an int, 1.0 is a float (duck typing)
Mathematical and Logical Operators can be used, e.g.
a = 5
b = 6
c = a + b
Can you write Python code for it?


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:
Sequence Data Types
List

List is an ordered sequence of items
Items don't have to be of the same type, because actually it's a list of references
Definition of a list: list_a = [5, 3.0, 'Hello']
Indexing starts from 0
Indexing can be used to extract (and set) elements from the list, e.g. list_a[2] would give 'Hello'

```python
    #creating the list
    list_a = [5, 3.0, 'Hello']
#extract third element/object and create reference to it
hello_str = list_a[2]

#mutate list
list_a[2] = 'Good bye'

#print new list
print(list_a)

```
[5, 3.0, 'Good bye']
Can you write Python code for it?

# what is hello_str

# reverse indexing

# stepwise indexing (start:stop:step)


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:
Tuple

Tuples are immutable lists $\rightarrow$ can't be changed once created
Definition of a tuple: tuple_a = (5 , 3.0, 'Hello')

```python
    #create tuple
    tuple_a = (5, 3.0, 'Hello')
#extract third element/object and create reference to it
hallo_str = tuple_a[2]

#mutate it???
tuple_a[2] = 'Good bye'

python

TypeError                                 Traceback (most recent call last)
<ipython-input-16-2ae0e9084ab6> in <module>()
----> 1 tuple_a[2] = 'Good bye'
TypeError: 'tuple' object does not support item assignment
```
Dictionaries

a dictionary is an unordered collection of key:value pairs
it enables you to map keys and objects
a dictionary is mutable

python
my_dict = {'one':1, 'two':2, 'three':3}
Can you write Python code for it?

my_dict = {'one':1, 'two':2, 'three':3}
print(my_dict['one'])

# how to test if certain key is in dict
print('one' in my_dict)
print('four' in my_dict)


I am working on the file "PythonIntro/20171027_PythonIntro.ipynb".
The first task is:
you see: y is not only a number, it has a lot of methods which we can use
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
<hr style="border: thin solid black;">
</hr>
Iteration and Loops

examples
generators

In Python, iteration happens with the help of iterators, similar to the Java Iterator class. While syntax is very similar to C.
Can you write Python code for it?

for i in range(4):
    print(i)

for i in range(1,3):
    print(i)


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
<hr style="border: thin solid black;">
</hr>
List Comprehension and Lisp Style Functional Programming

List comprehension examples
Map
Filter

Python supports a powerful feature known as list comprehension - iterating through lists inline to produce results. It also supports Functional programming Map and Filter idioms, despite Guido's efforts to remove them.
Suppose we want a list with numbers 0 through 2000:
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:

Lists and Dictionaries
Python Lists vs Java/C Arrays:

List	Array

No length attribute 	 .length

can store multiple types	single type

extendable	need to know length at the time of creation

offers functions to append, extend, etc	need to define own functions

Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
For loops can also be used to iterate through lists without iterator functions like range.
Can you write Python code for it?

for el in l:
    print(el)

l = [1, 5, 7, 3, 2, 9]
for i in range(len(l)):
    print('l[{}] = {}'.format(i, l[i]))


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
In python, inline comments are made after a #, as opposed to the // from C.
Block comments are rare, and can be made with """ """ if required. This is useful for docstrings.
Can you write Python code for it?

a+c # adding an int and a string (types are implicit)


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Lists can be accessed in powerful ways, beyond the typical index retrieval common to C and Java.
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Now suppose we want to remove all multiples of 7 from this list.
Can you write Python code for it?

l = [x for x in range(20) if x%3 != 0]

l


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Objects and Init
Can you write Python code for it?

class Person:
    pass

class Lord(Person):
    def __init__(self, add='lord'):
        self.address_by = add

class Stark(Lord):
    def __init__(self, name, gender):
        self.name = name
        if (gender == 'm' or gender == 'M'):
            if (name == 'Jon Snow'):
                super().__init__('grace')
            else:
                super().__init__('lord')

        else:
            super().__init__('lady')

class Lannister(Lord):
    def __init__(self, name, gender):
        self.name = name
        if (gender == 'f' or gender == 'F'):
            if (name == 'Cersei Lannister'):
                super().__init__('grace')
            else:
                super().__init__('lady')

        else:
            super().__init__('lord')

js = Stark('Jon Snow', 'm')
js.address_by

tl = Lannister('Tyrion Lannister', 'm')
tl.address_by

ss = Stark('Sansa Stark', 'f')
ss.address_by


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Python allows you to reassign variables in the usual ways.
Can you write Python code for it?

c = 1

a+c

pi = 3.14
type(pi)

type('some string')

type(1)


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Question 1: what does 2 * * 3  do?   2^3?
Unlike C, Python doesnt require variable types to declared.
Can you write Python code for it?

a = 5
b = 6
c = 'When you play the Game of Thrones, you either win, or you die.'

a

b

c

a+b

a-b


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Question 2: Predict the output.
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Question 3. What is the difference between these two?
<hr style="border: thin solid black;">
</hr>
Functions

Similarities with C
Differences from C
Example

Python Functions: Similarities

Same principle of modularisation
Similar parameter lists
Return values

Python Functions: Differences

Function definiton - no need to explicitly specify return types, parameter types
overloading vs duck typing (default parameter values)
docstrings
functions are First Class Objects
Can you write Python code for it?

def factorial(n=5):
    """Function to return the factorial of a given number (Defaults to 5)"""
    if n <= 0:
        return 1
    else:
        return n*factorial(n-1)

print(factorial(3))
print(factorial(5))
print(factorial())


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Question 4. Write a function to print the nth fibonacci number.
What if input is to be taken from the user?
In python, we take user input using the input() function.
Can you write Python code for it?

n = input("Enter n: ")
f = factorial(int(n))
print(f)


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
Question 6. What if you try to access a dictionary with a nonexistent key value?
d['vaes-dothrak']
Can you write Python code for it?

d['vaes-dothrak'] = 'capital city of the dothraki, where weapons are forbidden'

d['vaes-dothrak']


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
The split function can be used to tokenize a string.
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
To print, we use the print function in Python3, or the print statement in Python2. We'll stick with the the Python3 syntax in this notebook.
Can you write Python code for it?


I am working on the file "PythonIntro/IntroToPython.ipynb".
The first task is:
We can also achieve this result using Lisp Style Map and Filter, and the usual lambda <params>: <expression> syntax.
Can you write Python code for it?

l = [x for x in range(20)]

list(filter(lambda x: x%3!=0, l))

l = [x for x in range(10)]
list(map(lambda x: 2*x+1, l))


I am working on the file "PythonNotebooks/CommunicationMaterial/plot_MLD_profilers.ipynb".
The first task is:
Logging
Can you write Python code for it?

def configure_log():
    logdir = './log/'
    if not(os.path.exists(logdir)):
        os.mkdir(logdir)
    logfilename = os.path.join(logdir, 'computeMLD.log')
    # create logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(logfilename)
    fh.setLevel(logging.WARNING)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.CRITICAL)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger


I am working on the file "PythonNotebooks/CommunicationMaterial/plot_MLD_profilers.ipynb".
The first task is:
The goal is to compute and represent the Mixed Layer Depth (MLD) from the profiles acquired by the Argo profilers.<br>
To do so, we will use the python-oceans packages, which has a function to compute the MLD.
Can you write Python code for it?

import numpy as np
import netCDF4
import matplotlib.pyplot as plt
import glob
import os
import seawater
import cmocean
from matplotlib import rcParams
from mpl_toolkits.basemap import Basemap
from matplotlib.ticker import FuncFormatter
import logging
import oceans
# %matplotlib inline
oceans.__version__


I am working on the file "PythonNotebooks/Data_Augmentation/Comp_Vision_Ishan_Handa_DataAugmentation(+ROC_modified).ipynb".
The first task is:
Comparison with sift matching scores.
Can you write Python code for it?

beaver_sift_positive_csv = '/Users/ishanhanda/Documents/NYU_Fall16/Comp_Vision/Project/ProjectWorkspace/DataSets/OUTPUTS/Beaver_sift_positive.csv'
beaver_sift_negative_csv = '/Users/ishanhanda/Documents/NYU_Fall16/Comp_Vision/Project/ProjectWorkspace/DataSets/OUTPUTS/Beaver_sift_negative.csv'

print('Beaver Positive Images Test Results\n')
reader = csv.reader(open(beaver_sift_positive_csv,"rt"))
temp = list(reader)
positive_sift_data = numpy.array(temp).astype('float').flatten()
positive_sift_length = len(positive_sift_data)

print('\nBeaver positive test samples count: {}'.format(positive_sift_length))

print('\n\nBeaver Negative Images Test Results\n')
reader = csv.reader(open(beaver_sift_negative_csv,"rt"))
temp = list(reader)
negative_sift_data = numpy.array(temp).astype('float').flatten()
negative_sift_length = len(negative_sift_data)

print('\nBeaver negative test samples count: {}'.format(negative_sift_length))

TPRs_sift = [None] * len(thresholds)
FPRs_sift = [None] * len(thresholds)

for i in range(0, len(thresholds)):
    test_positive = positive_sift_data[positive_sift_data >= thresholds[i]]
    tpr = len(test_positive) / len(positive_sift_data)
    TPRs_sift[i] = tpr # This is the calculated TPR value for threshold level i in sample j

    test_negative = negative_sift_data[negative_sift_data >= thresholds[i]]
    fpr = len(test_negative) / len(negative_sift_data)
    FPRs_sift[i] = fpr # This is the calculated FPR value for threshold level i in sample j

print('\n\nPLOTTING ROC')
fig = plt.figure(figsize=(10,8))
p1 = plt.scatter(FPRs, TPRs, color='red', s=5)
plt.plot(FPRs, TPRs, color='red')
p2 = plt.scatter(FPRs_sift, TPRs_sift, color='green', s=5)
plt.plot(FPRs_sift, TPRs_sift, color='green')
plt.xticks(numpy.arange(0, 1.1, 0.1))
plt.yticks(numpy.arange(0, 1.1, 0.1))
plt.legend((p1, p2), ('IBM Watson VR', 'Sift Matching'))
plt.grid()
plt.ylabel('TPR')
plt.xlabel('FPR')
plt.title('IBM Watson VR Sift Matching ROC')
pylab.savefig('Sift_Vs_IBM_VR.png')
plt.show()


I am working on the file "PythonNotebooks/Data_Augmentation/Comp_Vision_Ishan_Handa_DataAugmentation(+ROC_modified).ipynb".
The first task is:
Now calculating TPR and FNR for the first positive test
Can you write Python code for it?

import pylab

TPRs = [None] * len(thresholds)
FPRs = [None] * len(thresholds)

TPRs_aug = [None] * len(thresholds)
FPRs_aug = [None] * len(thresholds)

for i in range(0, len(thresholds)):
    test_positive = positive_data[positive_data >= thresholds[i]]
    tpr = len(test_positive) / len(positive_data)
    TPRs[i] = tpr # This is the calculated TPR value for threshold level i in sample j

    test_negative = negative_data[negative_data >= thresholds[i]]
    fpr = len(test_negative) / len(negative_data)
    FPRs[i] = fpr # This is the calculated FPR value for threshold level i in sample j

    test_positive_aug = positive_augmented_data[positive_augmented_data >= thresholds[i]]
    tpr_a = len(test_positive_aug) / len(positive_augmented_data)
    TPRs_aug[i] = tpr_a # This is the calculated TPR value for threshold level i in sample j

    test_negative_aug = negative_augmented_data[negative_augmented_data >= thresholds[i]]
    fpr_a = len(test_negative_aug) / len(negative_augmented_data)
    FPRs_aug[i] = fpr_a # This is the calculated FPR value for threshold level i in sample j

print('\n\nPLOTTING ROC')
fig = plt.figure(figsize=(10,8))
p1 = plt.scatter(FPRs, TPRs, color='red', s=5)
plt.plot(FPRs, TPRs, color='red')
p2 = plt.scatter(FPRs_aug, TPRs_aug, color='green', s=5)
plt.plot(FPRs_aug, TPRs_aug, color='green')
plt.xticks(numpy.arange(0, 1.1, 0.1))
plt.yticks(numpy.arange(0, 1.1, 0.1))
plt.legend((p1, p2), ('Original', 'Augmented'))
plt.grid()
plt.ylabel('TPR')
plt.xlabel('FPR')
plt.title('Augmented Vs Original ROC')
pylab.savefig('Rotation_augmetended_ROC.png')
plt.show()


I am working on the file "PythonNotebooks/Data_Augmentation/Comp_Vision_Ishan_Handa_DataAugmentation(+ROC_modified).ipynb".
The first task is:
Now we need to define the threshold points over which the ROC will be plotted.
Can you write Python code for it?

# Here we are defining preset threshold levels for which TPR and FPR values will be calculated
thresholds = numpy.arange(0.0,1.0,0.005)
print('Thresholds: {}'.format(thresholds))


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/IndexFile_Folium_Visalization-checkpoint.ipynb".
The first task is:
Finally we can create the map where we will see the locations of the platforms as well as the corresponding file names.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/IndexFile_Folium_Visalization-checkpoint.ipynb".
The first task is:
For each data file, the positions are defined as a bounding box.

To define the position shown on the map, we use the mean of the stored geospatial_lat/lon_min/max for each dataset.
Can you write Python code for it?

lon_min = dataindex['geospatial_lon_min']
lon_max = dataindex['geospatial_lon_max']
lat_min = dataindex['geospatial_lat_min']
lat_max = dataindex['geospatial_lat_max']
lonmean, latmean = 0.5*(lon_min + lon_max), 0.5*(lat_min + lat_max)


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/IndexFile_Folium_Visalization-checkpoint.ipynb".
The first task is:
Select by data provider
We create a list of indices corresponding to the entries with a provider belonging to the list specified at the beginning.
Can you write Python code for it?

indexlist = []
for np, provider in enumerate(dataindex['provider']):
    matching = [s for s in dataproviderlist if s in provider]
    if matching:
        indexlist.append(np)


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/IndexFile_Folium_Visalization-checkpoint.ipynb".
The first task is:
Selection criteria
Here we show how the data positions can be selected prior to the plot.<br>
The example explains the selection by data providers, but that can be generalised to other properties.
Provider
The list dataprovider contains the name of the providers we want to keep for the plot.
Can you write Python code for it?

dataproviderlist = ['IEO', 'INSTITUTO ESPANOL DE OCEANOGRAFIA', 'SOCIB']


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/read_CMEMS_indexfile-checkpoint.ipynb".
The first task is:
Selection of a data file based on coordinates
Let's assume we want to have the list of files corresponding to measurements off the northern of Lybia.<br/>
We define a rectangular box containg the data:
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/read_CMEMS_indexfile-checkpoint.ipynb".
The first task is:
To read the index file (comma separated values), we will try with the genfromtxt function.
Can you write Python code for it?

import numpy as np
dataindex = np.genfromtxt(indexfile, skip_header=6, unpack=True, delimiter=',', dtype=None, \
              names=['catalog_id', 'file_name', 'geospatial_lat_min', 'geospatial_lat_max',
                     'geospatial_lon_min', 'geospatial_lon_max',
                     'time_coverage_start', 'time_coverage_end',
                     'provider', 'date_update', 'data_mode', 'parameters'])


I am working on the file "PythonNotebooks/IndexFilePlots/.ipynb_checkpoints/read_CMEMS_indexfile-checkpoint.ipynb".
The first task is:
We create the projection, centered on the Mediterranean Sea in this case.
Can you write Python code for it?

m = Basemap(projection='merc', llcrnrlat=30., urcrnrlat=46.,
            llcrnrlon=-10, urcrnrlon=40., lat_ts=38., resolution='i')
lonmean, latmean = 0.5*(lon_min + lon_max), 0.5*(lat_min + lat_max)
lon2plot, lat2plot = m(lonmean, latmean)


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
Could do intersection of the list, but for that we need to specify the provider name as specified in the index file.
Visualization
Finally, we create the map object.<br>
The map is centered on the Mediterranean Sea, this has to be changed according to the region of interest and the index file we consider.
Can you write Python code for it?

map = folium.Map(location=[39.5, 2], zoom_start=8)
cntr = 0
for i in indexlist:
    curr_data = dataindex[i]
    link = curr_data[1]

    last_idx_slash = link.rfind('/')

    ncdf_file_name = link[last_idx_slash+1::]
    folium.Marker( location = [latmean[i], lonmean[i]], popup=ncdf_file_name).add_to(map)


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
Finally we can create the map where we will see the locations of the platforms as well as the corresponding file names.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
For each data file, the positions are defined as a bounding box.

To define the position shown on the map, we use the mean of the stored geospatial_lat/lon_min/max for each dataset.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
Here we could also add something for the time or space domain.
Load and prepare data
Since the index_latest.txt is a formatted file, we use the numpy function genfromtxt to extract the data from the document.
Can you write Python code for it?

dataindex = np.genfromtxt(indexfile, skip_header=6, unpack=True, delimiter=',', dtype=None, \
              names=['catalog_id', 'file_name', 'geospatial_lat_min', 'geospatial_lat_max',
                     'geospatial_lon_min', 'geospatial_lon_max',
                     'time_coverage_start', 'time_coverage_end',
                     'provider', 'date_update', 'data_mode', 'parameters'])


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
Select by data provider
We create a list of indices corresponding to the entries with a provider belonging to the list specified at the beginning.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/IndexFile_Folium_Visalization.ipynb".
The first task is:
Selection criteria
Here we show how the data positions can be selected prior to the plot.<br>
The example explains the selection by data providers, but that can be generalised to other properties.
Provider
The list dataprovider contains the name of the providers we want to keep for the plot.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/plot_positions_latest_global.ipynb".
The first task is:
File reading
We create a list of the files available in the directory:
Can you write Python code for it?

datadir = os.path.expanduser(datadir)
filelist = sorted(glob.glob(datadir + '*nc'))
nfiles = len(filelist)
print("Number of files = %u" % (nfiles))


I am working on the file "PythonNotebooks/IndexFilePlots/plot_positions_latest_global.ipynb".
The first task is:
It is interesting to see the highly variable coverage.

For example near the Equator in the Atlantic Ocean, the coverage is very low.
Plot by platform
The idea is to have a different color depending on the platform type:
* drifting buoys,
* gliders,
* moorings...
To do so, we will create a list of files for each parameter.

There is an extensive description of all the data types in this document.
Can you write Python code for it?

datatypelist = ('BA', 'BO', 'CT', 'DB', 'DC', 'FB', 'GL', 'MO', 'ML', 'PF', 'RF', 'TE', 'TS', 'XB')
for datatype in datatypelist:
    filelist = sorted(glob.glob(datadir + '*LATEST_*_' + datatype + '*nc'))
    nfiles = len(filelist)
    print("Number of files of type %s = %u" % (datatype, nfiles))


I am working on the file "PythonNotebooks/IndexFilePlots/plot_positions_latest_global.ipynb".
The first task is:
Pie chart
It is also useful to have a pie chart showing the relative importance of each data type.
Can you write Python code for it?

fig2 = plt.figure(figsize=(10, 8))
plt.pie(nfiles, labels=datatypename.values(), colors=colorlist,
        autopct='%1.1f%%', startangle=90)
plt.savefig('./figures/platform_piechart_20151201.png', dpi=300)
plt.show()


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
According to the file names, we have 7 profiling drifters available in the area. <br/>
To check, we replot the data only in the selected box:
Can you write Python code for it?

m2 = Basemap(projection='merc', llcrnrlat=32., urcrnrlat=34.,
            llcrnrlon=12, urcrnrlon=15., lat_ts=38., resolution='h')
lon2plot, lat2plot = m2(lonmean[goodcoordinates], latmean[goodcoordinates])

fig = plt.figure(figsize=(10,8))
m2.plot(lon2plot, lat2plot, 'ko', markersize=4)
m2.drawcoastlines(linewidth=0.5, zorder=3)
m2.fillcontinents(zorder=2)

m2.drawparallels(np.arange(-90.,91.,0.5), labels=[1,0,0,0], linewidth=0.5, zorder=1)
m2.drawmeridians(np.arange(-180.,181.,0.5), labels=[0,0,1,0], linewidth=0.5, zorder=1)
plt.show()


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
And we create a plot showing all the data locations.
Can you write Python code for it?

fig = plt.figure(figsize=(10,8))
m.plot(lon2plot, lat2plot, 'ko', markersize=2)
m.drawcoastlines(linewidth=0.5, zorder=3)
m.fillcontinents(zorder=2)

m.drawparallels(np.arange(-90.,91.,2.), labels=[1,0,0,0], linewidth=0.5, zorder=1)
m.drawmeridians(np.arange(-180.,181.,3.), labels=[0,0,1,0], linewidth=0.5, zorder=1)
plt.show()


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
Map of observations
Can you write Python code for it?

lon_min = dataindex['geospatial_lon_min']
lon_max = dataindex['geospatial_lon_max']
lat_min = dataindex['geospatial_lat_min']
lat_max = dataindex['geospatial_lat_max']


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
Selection of a data file based on coordinates
Let's assume we want to have the list of files corresponding to measurements off the northern of Lybia.<br/>
We define a rectangular box containg the data:
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
The generation of the file list is direct:
Can you write Python code for it?

goodfilelist = dataindex['file_name'][goodcoordinates]
print goodfilelist


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
To read the index file (comma separated values), we will try with the genfromtxt function.
Can you write Python code for it?


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
We create the projection, centered on the Mediterranean Sea in this case.
Can you write Python code for it?

m = Basemap(projection='merc', llcrnrlat=30., urcrnrlat=46.,
            llcrnrlon=-10, urcrnrlon=40., lat_ts=38., resolution='l')
lonmean, latmean = 0.5*(lon_min + lon_max), 0.5*(lat_min + lat_max)
lon2plot, lat2plot = m(lonmean, latmean)


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
We import the modules necessary for the plot.
Can you write Python code for it?

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap


I am working on the file "PythonNotebooks/IndexFilePlots/read_CMEMS_indexfile.ipynb".
The first task is:
then we look for the observations within this box:
Can you write Python code for it?

import numpy as np
goodcoordinates = np.where( (lonmean>=box[0]) & (lonmean<=box[1]) & (latmean>=box[2]) & (latmean<=box[3]))
print goodcoordinates


I am working on the file "PythonNotebooks/PlatformPlots/Plot_TimeSeries1.ipynb".
The first task is:
Basic plot
We create the most simple plot, without any additional option.
Can you write Python code for it?

fig = plt.figure()
plt.plot(time2, temperature_values)
plt.ylabel(temperature_units)


I am working on the file "PythonNotebooks/PlatformPlots/Plot_TimeSeries1.ipynb".
The first task is:
Final version
We want to add a title containing the coordinates of the station. Longitude and latitude are both stored as vectors, but we will only keep the mean position to be included in the title.
LaTeX syntax can be used, as in this example, with the degree symbol.
Can you write Python code for it?

with netCDF4.Dataset(datafile, 'r') as ds:
    lon = ds.variables['LONGITUDE'][:]
    lat = ds.variables['LATITUDE'][:]
figure_title = r'Temperature evolution at \n%s$^\circ$E, %s$^\circ$N' % (lon.mean(), lat.mean())
print figure_title