I am working on the file "03 - Cross-validation.ipynb".
The first task is:
There are other ways to do cross-valiation
Can you write Python code for it?

from sklearn.cross_validation import ShuffleSplit

shuffle_split = ShuffleSplit(len(X), 10, test_size=.4)
cross_val_score(LinearSVC(), X, y, cv=shuffle_split)

from sklearn.cross_validation import StratifiedKFold, KFold, ShuffleSplit

def plot_cv(cv, n_samples):
    masks = []
    for train, test in cv:
        mask = np.zeros(n_samples, dtype=bool)
        mask[test] = 1
        masks.append(mask)
    plt.figure(figsize=(10, 4))
    plt.subplots_adjust(left=0, bottom=0, right=1, top=1)
    plt.imshow(masks, interpolation='none')

plot_cv(StratifiedKFold(y, n_folds=5), len(y))

plot_cv(KFold(len(iris.target), n_folds=5), len(iris.target))

plot_cv(ShuffleSplit(len(iris.target), n_iter=20, test_size=.2),
        len(iris.target))


I am working on the file "03 - Data 1.ipynb".
The first task is:
Notice that the totals are of type object (strings) instead of numbers.
Can you write Python code for it?


I am working on the file "03 - Data 1.ipynb".
The first task is:
Now the data can be explored using matplotlib and interact.  The following function plots the costs of the selected parameter type.
Can you write Python code for it?

%matplotlib inline
from matplotlib import pyplot as plt
from pandas import DataFrame

def plot_by(df, column='Dept Name', count=10, ascending=False):

    # Group the data by the column specified and sum the totals.
    data = df.groupby(column)['Total'].sum().dropna()

    # Sort the data.
    data = DataFrame(data, columns=['Total']).sort('Total', ascending=ascending)

    # Plot the subset of the sorted data that the user is interested in.
    data = data[:count].plot(kind='bar')

    # Plot settings.
    plt.title('%s Costs' % column)
    plt.ylabel('Cost ($)')

from IPython.html.widgets import interact, fixed
interact(plot_by, df=fixed(df), column=df.columns.tolist(), count=(5,15));


I am working on the file "03 - Data 1.ipynb".
The first task is:
You can take a quick look at the first 5 rows of the data set using a slice.  Pandas knows how to display this as a table in IPython.
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:

    EXERCISE: Add a column `density` with the population density (note: population column is expressed in millions)

    EXERCISE: Select the capital and the population column of those countries where the density is larger than 300

    EXERCISE: Add a column 'density_ratio' with the ratio of the density to the mean density

    EXERCISE: Change the capital of the UK to Cambridge

    EXERCISE: Select all countries whose population density is between 100 and 300 people/km²

Some other useful methods: isin and string methods
The isin method of Series is very useful to select rows that may contain certain values:
Can you write Python code for it?

s = countries['capital']

s.isin?

s.isin(['Berlin', 'London'])


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Boolean indexing
To select data fulfilling specific criteria, one can use the bolean indexing. This is best illustrated on 1D arrays; for example, lets select only positive elements of a:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Boolean indexing (filtering)
Like a where clause in SQL. The indexer (or boolean mask) should be 1-dimensional and the same length as the thing being indexed.
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
But, slicing accesses the rows:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Fancy indexing
Apart from indexing with integers and slices NumPy also supports indexing with arrays of integers (so-called fancy indexing). For example, to get the 2nd and 4th element of a:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
For an overview of all string methods, see: http://pandas.pydata.org/pandas-docs/stable/api.html#string-handling

    EXERCISE: Select all countries that have capital names with more than 7 characters

    EXERCISE: Select all countries that have capital names that contain the character sequence 'am'

Pitfall: chained indexing (and the 'SettingWithCopyWarning')
Can you write Python code for it?

countries.loc['Belgium', 'capital'] = 'Ghent'

countries

countries['capital']['Belgium'] = 'Antwerp'

countries

countries[countries['capital'] == 'Antwerp']['capital'] = 'Brussels'

countries


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Indexing DataFrame
Can you write Python code for it?

data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'],
        'population': [11.3, 64.3, 81.3, 16.9, 64.9],
        'area': [30510, 671308, 357050, 41526, 244820],
        'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'London']}
countries = pd.DataFrame(data)
countries

countries = countries.set_index('country')
countries


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Let's say we want to select all data for which the capital starts with a 'B'. In Python, when having a string, we could use the startswith method:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
More on NumPy indexing
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Multiple criteria can be also combine in one query:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Selecting by position with iloc works similar as indexing numpy arrays:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Setting the index to the country names:
Can you write Python code for it?

countries = countries.set_index('country')
countries


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Similarly, boolean indexing can be used to filter the Series. Lets select countries with population of more than 20 millions:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
So as a summary, [] provides the following convenience shortcuts:

Series: selecting a label: s[label]
DataFrame: selecting a single or multiple columns: df['col'] or df[['col1', 'col2']]
DataFrame: slicing the rows: df['row_label1':'row_label2'] or df[mask]

Systematic indexing with loc and iloc
When using [] like above, you can only select from one axis at once (rows or columns, not both). For more advanced indexing, you have some extra attributes:

loc: selection by label
iloc: selection by position

These methods index the different dimensions of the frame:

df.loc[row_indexer, column_indexer]
df.iloc[row_indexer, column_indexer]

Selecting a single element:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
So as a summary, [] provides the following convenience shortcuts:

NumPy/`Series`
`DataFrame`

Integer index
`data[label]`
single element
single **column**

Slice
`data[label1:label2]`
sequence
one or more **rows**

Fancy indexing
`data[[label1,label2]]`
sequence
one or more **columns**

Boolean indexing
`data[mask]`
sequence
one or more **rows**

    EXERCISE: Calculate the area of Germany relative to the total area of all other countries in the data frame. *Hint*: you can compare the index of the data frame to any string

Systematic indexing with loc and iloc
When using [] like above, you can only select from one axis at once (rows or columns, not both). For more advanced indexing, you have some extra attributes:

loc: selection by label
iloc: selection by position

These methods index the different dimensions of the frame:

df.loc[row_indexer, column_indexer]
df.iloc[row_indexer, column_indexer]

Selecting a single element:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
Some notes on selecting data
One of pandas' basic features is the labeling of rows and columns, but this makes indexing also a bit more complex compared to numpy. We now have to distuinguish between:

selection by label
selection by position.

data[] provides some convenience shortcuts
For a DataFrame, basic indexing selects the columns.
Selecting a single column:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
The different indexing methods can also be used to assign data:
Can you write Python code for it?

countries2 = countries.copy()
countries2.loc['Belgium':'Germany', 'population'] = 10

countries2


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
This can then be used to filter the dataframe with boolean indexing:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
We can also select rows similarly to the boolean indexing in numpy. The boolean mask should be 1-dimensional and the same length as the thing being indexed. Boolean indexing of DataFrame  can be used like the WHERE clause of SQL to select rows matching some criteria:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
We can use fancy indexing with the rich index:
Can you write Python code for it?


I am working on the file "03 - Indexing and selecting data.ipynb".
The first task is:
or multiple columns:
Can you write Python code for it?


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
Are features predictive?
Can you write Python code for it?

from sklearn.linear_model import RandomizedLasso

model = RandomizedLasso(alpha=0.1)
model.fit(energy_features, energy_labels["heating_load"])
names = list(energy_features)

print("Features sorted by their score:")
print(sorted(zip(map(lambda x: round(x, 4), model.scores_),
                 names), reverse=True))

model = RandomizedLasso(alpha=0.1)
model.fit(energy_features, energy_labels["cooling_load"])
names = list(energy_features)

print("Features sorted by their score:")
print(sorted(zip(map(lambda x: round(x, 4), model.scores_),
                 names), reverse=True))


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
Choosing Alpha
We can search for the best parameter using the ModelCV which is a form of Grid Search, but uses a more efficient form of leave-one-out cross-validation.
Can you write Python code for it?

from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV

alphas = np.logspace(-10, -2, 200)

ridge = RidgeCV(alphas=alphas)
lasso = LassoCV(alphas=alphas)
elnet = ElasticNetCV(alphas=alphas)

for model in (ridge, lasso, elnet):
    model.fit(X_train, y_train)

    mse = mean_squared_error(y_test, model.predict(X_test))
    r2 = model.score(X_test, y_test)

    print("{}\nAlpha: {:0.3f} | MSE: {:0.3f} | R2: {:0.3f}".format(model, model.alpha_, mse, r2))

clf = Ridge(fit_intercept=False)
errors = []
for alpha in alphas:
    splits = tts(X, y, test_size=0.2)
    X_train, X_test, y_train, y_test = splits
    clf.set_params(alpha=alpha)
    clf.fit(X_train, y_train)
    error = mean_squared_error(y_test, clf.predict(X_test))
    errors.append(error)

axe = plt.gca()
axe.plot(alphas, errors)


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
Evaluating Models
Can you write Python code for it?

from sklearn.metrics import mean_squared_error, r2_score
from sklearn.cross_validation import train_test_split as tts

X_train, X_test, y_train, y_test = tts(X, y)
model = LinearRegression()
model.fit(X_train, y_train)

mse = mean_squared_error(y_test, model.predict(X_test))
r2 = model.score(X_test, y_test)

print("MSE: {:0.3f} | R2: {:0.3f}".format(mse, r2))


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
LASSO Regularization
Reducing bias is one thing, but what if the coefficients are very sparse? E.g. the more dimensions we add, the more space goes into the model.
Lasso prefers fewer parameters attempting to reduce the number of variables the solution depends on.
$min_w \frac{1}{2n}(\sum{(Xw-w)^2+\alpha ||w||_1}$

The term $\alpha‖w‖_1$ is the L1 norm, whereas in ridge we used the L2 norm, $\alpha‖w‖_2$.
See also Least Angle Regression (LARS) as similar.
Can you write Python code for it?

from sklearn.linear_model import Lasso

model = Lasso(alpha=0.5)
model.fit(X_train, y_train)

mse = mean_squared_error(y_test, model.predict(X_test))
r2 = model.score(X_test, y_test)

print("{}\nMSE: {:0.3f} | R2: {:0.3f}".format(model, mse, r2))


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
Regularization

As we increase the complexity of the model we reduce the bias but increase the variance of the model.
Variance: the tendency for the model to fit to noise (randomness) -- overfit.
Introduce a parameter to penalize complexity in the function being minimized.

Vector Norm
Describes the length of the vector.

L1: sum of the absolute values of components
L2: euclidian distance from the origin
L∞: maximal absolute value component
Can you write Python code for it?

X_train, X_test, y_train, y_test = tts(Xc, yc)
model = LinearRegression()
model.fit(X_train, y_train)

mse = mean_squared_error(y_test, model.predict(X_test))
r2 = model.score(X_test, y_test)

print("{}\nMSE: {:0.3f} | R2: {:0.3f}".format(model,mse, r2))


I am working on the file "03 - Regression Analysis.ipynb".
The first task is:
Ridge Regularization
Prevent overfit/collinearity by penalizing the size of coefficients - minimize the penalized residual sum of squares:
Said another way, shrink the coefficients to zero.
$min_w (||Xw-y||_2)^2 + (\alpha||w||_2)^2$
Where 𝛼 > 0 is complexity parameter that controls shrinkage. The larger 𝛼, the more robust the model to collinearity.
Alpha influences the the bias/variance tradeoff: the larger the ridge alpha, the higher the bias and the lower the variance.
Can you write Python code for it?

from sklearn.linear_model import Ridge

model = Ridge(alpha=0.1)
model.fit(X_train, y_train)

mse = mean_squared_error(y_test, model.predict(X_test))
r2 = model.score(X_test, y_test)

print("{}\nMSE: {:0.3f} | R2: {:0.3f}".format(model, mse, r2))


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
And, just as easily, visualise it with draw_spring(), where spring is a reference to the idea that edges in the network are treated like physical springs, with elasticity/compressability related to the weights of the connections:
Can you write Python code for it?


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
It's isolated the people who appear in the book at Number 4, Privet Drive. Fun!
We can do stuff like illustrate the communicability of one character with another - We would expect that characters which don't spend much time together in the book would have a harder time communicating with one another than those who spend a lot of time together, illustrated by a smaller communicability value:
Can you write Python code for it?

comms = nx.communicability(G)

print(comms["('Vernon ',)"]["('Dumbledore ',)"])
print(comms["('Harry ',)"]["('Hermione ',)"])


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
The next cell can be used to set up a locally hosted version of that d3.js script.
It's a super-simple, two-line bash script which uses python's builtin http.server module to run the javascript visualisation code in the browser on your machine.
We dumped our graph data into a file called 'bookworm.json' in one of the cells above - that file can now processed by 'index.html' (printed above), which displays the data using the d3.js javascript library.
Can you write Python code for it?

%%bash
cd bookworm/d3/
python -m http.server


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
Very nice... ish. There's more that could be done to clean up the visualisation and make it pretty, but it's fine for now.
One of the nicest things about NetworkX is all of its builtin network analysis functionality. For example, we can use pagerank or hits to give us the most 'important' or 'central' nodes in the network. These algorithms were originally developed to analyse linked networks of websites, but they can just as easily be applied to stations in transport networks, streets in cities, similar products in ecommerce systems, friends in social circles, or connected characters in books.
Can you write Python code for it?

pd.Series(nx.pagerank(G)).sort_values(ascending=False)[:5]

a, b = nx.hits(G)
pd.Series(a).sort_values(ascending=False)[:5]


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
We can write that dictionary out to a .json file in the project's d3 directory using the json package:
Can you write Python code for it?

import json

with open('bookworm/d3/bookworm.json', 'w') as fp:
    json.dump(d3_dict, fp)


I am working on the file "03 - Visualising and Analysing Networks.ipynb".
The first task is:
get_interaction_df() is defined in bookworm/build_network.py, and works by searching through the provided cooccurence matrix for interactions with strength above a specified threshold.
We can load that interaction dataframe into a NetworkX Graph using the super simple from_pandas_dataframe() function:
Can you write Python code for it?

G = nx.from_pandas_dataframe(interaction_df,
                             source='source',
                             target='target')


I am working on the file "03 Classification.ipynb".
The first task is:
How do we evaluate how good the classification task performed?
For binary classification, the Receiver-Operator Characteristic curve is a great way to evaluate a classification task.
For multi-label classification, which is the case we have here, accuracy score is a great starting place.
Can you write Python code for it?

# Let's first take a look at the accuracy score: the fraction that were classified correctly.
accuracy_score(lb.inverse_transform(Y_test), lb.inverse_transform(preds))


I am working on the file "03 Classification.ipynb".
The first task is:
Problem Statement
There are influenza viruses that are collected from the "environment", or have an "unknown" host. How do we infer which hosts it came from? Well, that sounds like a Classification problem.
Can you write Python code for it?

# Load the sequences into memory
sequences = [s for s in SeqIO.parse('data/20160127_HA_prediction.fasta', 'fasta') if len(s.seq) == 566]  # we are cheating and not bothering with an alignment.
len(sequences)

# Load the sequence IDs into memory
seqids = [s.id for s in SeqIO.parse('data/20160127_HA_prediction.fasta', 'fasta') if len(s.seq) == 566]
len(seqids)

# Cast the sequences as a MultipleSeqAlignment object, and then turn that into a pandas DataFrame.
# Note: this cell takes a while.
seq_aln = MultipleSeqAlignment(sequences)
seq_df = pd.DataFrame(np.array(seq_aln))
seq_df.head()

# Transform the df into isoelectric point features.
seq_feats = seq_df.replace(isoelectric_points.keys(), isoelectric_points.values())
seq_feats.index = seqids
seq_feats.head()

# Quick check to make sure that we have no strings:
for c in seq_feats.columns:
    letters = set(seq_feats[c])
    for item in letters:
        assert not isinstance(item, str)

# Let us now load our labels.
labels = pd.read_csv('data/20160127_HA_prediction.csv', parse_dates=['Collection Date'])
labels['Host Species'] = labels['Host Species'].str.replace('IRD:', '').str.replace('/Avian', '')
labels['Sequence Accession'] = labels['Sequence Accession'].str.replace('*', '')
labels.set_index('Sequence Accession', inplace=True)
labels.head()

# Let's join in the labels so that we have everything in one big massive table.
data_matrix = seq_feats.join(labels['Host Species'], how='inner')
data_matrix.head()

# Quickly inspect the different labels under "host species"
# set(data_matrix['Host Species'])

# We will want to predict the labels for: "Avian", "Bird", "Environment", "Unknown", "null"
unknown_labels = ['Avian', 'Bird', 'Environment', 'Unknown', 'null']
known_labels = set(data_matrix['Host Species']) - set(unknown_labels)

# Let's further split the data into the "unknowns" and the "knowns"
unknowns = data_matrix[data_matrix['Host Species'].isin(unknown_labels)]
knowns = data_matrix[data_matrix['Host Species'].isin(known_labels)]

# Finally, we want to...


I am working on the file "03 Classification.ipynb".
The first task is:
Train/Test Split
We're almost ready for training a machine learning model to classify the unknown hosts based on their sequence.
Here's the proper procedure.

Split the labelled data into a training and testing set. (~70 train/30 test to 80 train/20 test)
Train and evaluate a model on the training set.
Make predictions on the testing set, evaluate the model on testing set accuracy.

This procedure is known as cross-validation, and is a powerful, yet cheap & easy method for evaluating how good a particular supervised learning model works.
Can you write Python code for it?

# Split the data into a training and testing set.
X_cols = [i for i in range(0,566)]
X = knowns[X_cols]
Y = lb.transform(knowns['Host Species'])

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)

# Train a Random Forest Classifier.
# Note: This cell takes a while; any questions?

# Initialize the classifier object.
clf = RandomForestClassifier()

# Train (i.e. "fit") the classifier to the training Xs and Ys
clf.fit(X_train, Y_train)

# Make predictions on the test X
preds = clf.predict(X_test)
preds

lb.inverse_transform(preds)


I am working on the file "03 Classification.ipynb".
The first task is:
What about those sequences for which the hosts were unknown?
We can run the predict(unknown_Xs) to predict what their hosts were likely to be, given their sequence.
Can you write Python code for it?

unknown_preds = clf.predict(unknowns[X_cols])  # make predictions; note: these are still dummy-encoded.
unknown_preds = lb.inverse_transform(unknown_preds)  # convert dummy-encodings back to string labels.
unknown_preds


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Compute and Plot All Items
Can you write Python code for it?

for item in items:
    for view in views:
        print(item + '_' + view)
        plot(item,view)
        plt.show()


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Compute and Save
Issues:
* remove black color from transparent items, e.g.:
  * poland_spring
  * ...
Can you write Python code for it?

import cv2, glob
from utils import imread_rgb, imread_gray, compute_colors

def worker(item):
    folder = ITEM_FOLDER + '/' + item + '/'
    files = glob.glob(folder + '*.png')
    for filename in files:
        image_RGB = imread_rgb(filename)
        if not image_RGB is None:
            image_RGB = cv2.resize(image_RGB,(RESIZE_X,RESIZE_Y))
            file_mask = filename[:-4] + '_mask.pgm'
            mask = imread_gray(file_mask)
            hist, cc = compute_colors(image_RGB, mask)
            dominant_colors = {'hist': hist,
                               'cluster_centers': map(lambda t: list(t), cc)}
            with open(filename[:-4] + '_dc.json', 'w') as outfile:
                json.dump(dominant_colors, outfile)

%%time
from multiprocessing import Pool

print('Computing Dominant colors of images')
print('* resized to %d x %d' % (RESIZE_X,RESIZE_Y))
print('* LAB space')
print('* KMeans')
#print('* MiniBatchKMeans')
pool_size = 6
pool = Pool(pool_size)
result = []
for item in items:
    result.append( pool.apply_async(worker, (item,)) )
pool.close()
pool.join()
for r in result:
     r.get()


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Computing Test
Can you write Python code for it?

from matplotlib import pyplot as plt
%matplotlib inline

import cv2, numpy as np
from ipywidgets import interact
from utils import imread_rgb, imread_gray, compute_colors, plot_colors

def compute_and_plot(item,view):
    prefix = ITEM_FOLDER + '/' + item + '/' + item + '_' + view
    filename = prefix + '.png'
    image_RGB = imread_rgb(filename)
    if not image_RGB is None:
        image_RGB = cv2.resize(image_RGB,(RESIZE_X,RESIZE_Y))
        filename = prefix + '_mask.pgm'
        mask = imread_gray(filename)
        plt.subplot(121); plt.imshow(image_RGB); plt.axis('off');
        hist, cc = compute_colors(image_RGB, mask)
        bar = plot_colors(hist, cc)
        plt.subplot(122); plt.imshow(bar); plt.axis('off'); plt.title(item + '_' + view);

views = ['top_01','top-side_01','top-side_02','bottom_01','bottom-side_01','bottom-side_02']
interact(compute_and_plot,item=items,view=views);


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Plot All Items
Can you write Python code for it?

for item in items:
    for view in views:
        print(item + '_' + view)
        load_and_plot(item,view)
        plt.show()


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Plot File
Can you write Python code for it?

from matplotlib import pyplot as plt
%matplotlib inline

import cv2, numpy as np
from ipywidgets import interact
from utils import imread_rgb, plot_colors

def load_and_plot(item,view):
    try:
        prefix = ITEM_FOLDER + '/' + item + '/' + item + '_' + view
        filename = prefix + '.png'
        image_RGB = imread_rgb(filename)
        if not image_RGB is None:
            with open(filename[:-4] + '_dc.json', 'r') as infile:
                dc = json.load(infile)
            hist = dc['hist']
            cc = dc['cluster_centers']
            bar = plot_colors(hist, cc)
            plt.subplot(121); plt.imshow(image_RGB); plt.axis('off');
            plt.subplot(122); plt.imshow(bar); plt.axis('off');
    except (IOError, OSError):
        print('File not found')

views = ['top_01','top-side_01','top-side_02','bottom_01','bottom-side_01','bottom-side_02']
interact(load_and_plot,item=items,view=views);


I am working on the file "03 Compute Items Dominant Colors.ipynb".
The first task is:
Statistics???
Can you write Python code for it?

import glob
from utils import ...

item_view = []
VVV = []
for item in items:
    folder = ITEM_FOLDER + '/' + item + '/'
    files = glob.glob(folder + '*_XXX.YYY')
    for filename in files:
        ...
        item_view.append(filename)
        VVV.append(len(des))

from matplotlib import pyplot as plt
%matplotlib inline
plt.hist(VVV,bins=60);

[(ns, str(iv.split('/')[-1][:-9])) for ns, iv in sorted(zip(VVV,item_view), reverse=True) if ns>2000]

[(ns, str(iv.split('/')[-1][:-9])) for ns, iv in sorted(zip(VVV,item_view), reverse=True) if ns<50]


I am working on the file "03 Homework.ipynb".
The first task is:
10.Zeige nur die Bevölkerung der Stadt Genf an
Can you write Python code for it?

dct_lst[1]['Bevölkerung']

b = 0

for elem in dct_lst:
    b = b + elem["Bevölkerung"] #Eingabe mittels Tab-Taste.
    print(b)

b


dct_lst = [{'Stadt': 'Zürich', 'Grösse': 396027, 'Kanton': 'Zürich'},
           {'Stadt': 'Genf', 'Grösse': 194565, 'Kanton': 'Genf'},
           {'Stadt': 'Basel', 'Grösse': 175131, 'Kanton': 'Basel-Stadt'},
           {'Stadt': 'Bern', 'Grösse': 140634, 'Kanton': 'Bern'},
           {'Stadt': 'Lausanne', 'Grösse': 135629, 'Kanton': 'Waadt'}]

dct_lst

for dct in dct_lst


I am working on the file "03 Homework.ipynb".
The first task is:
14.Ergänze die Städte-Dictionary-Liste mit Winterthur und Luzern
Can you write Python code for it?


I am working on the file "03 Homework.ipynb".
The first task is:
2.Mache dasselbe mit einer Liste aus 100 Elementen und ordne sie der Variabel b zu.
Can you write Python code for it?


I am working on the file "03 Homework.ipynb".
The first task is:
3.Füge beiden Listen folgenden String an: 'ich bin keine Zahl'
Can you write Python code for it?

a.append("ich bin keine Zahl")

a

b.append("ich bin keine Zahl")


I am working on the file "03 Homework.ipynb".
The first task is:
5.Verwandle jede Zahl in den Listen a und b von int in str?
Can you write Python code for it?

a = list(map(str, a))

a

b = list(map(str, b))
b

#Barnabys Lösung for x in a:
a = range(10)
a

#Barnabys Lösung: for loops! Sehr wichtig! Wir müssen in Liste reingehen und die Liste manipulieren.
empty_list = []
for element_in_the_list in a:
    new_element = str(element_in_the_list)
    empty_list.append(new_element)
empty_list


I am working on the file "03 Homework.ipynb".
The first task is:
6.Von der list b, zeige nur die letzten zehn Nummern an
Can you write Python code for it?


b = range(100)

str(b)

lange_leere_liste = []
for x in b:
    neues_element = str(x)
    lange_leere_liste.append(neues_element)

b[89:95]


I am working on the file "03 Homework.ipynb".
The first task is:
7.Von der folgenden Liste, zeige den zweit grössten Wert an
Can you write Python code for it?

#Schritt 1: sortieren Schritt 2: -2
c = range(100)
c = range(0,100)
c = list (range(100))
c

c[-2]

sorted(c, reverse=True) #Sortieren und die Reihenfolge ändern

c[1]

c[::2] #Jedes 2. Element.

c[::3] #Jedes 3. Element.

d = [23, 333, 567, 888]
d

#Python Panda als Hilfsmlittel bei Listen. Listen sind sehr praktisch.


I am working on the file "03 Homework.ipynb".
The first task is:
8.Multipliziere jede Nummer in dieser Liste, die kleiner ist als 100, mit 100; wenn die Nummern zwischen 100 und 1000 verwandle sie in eine String, und wenn sie grösser oder gleich 1000 ist, lösche sie.
Can you write Python code for it?

#Umwandlung zurück in integer
b = list(map(int, b))

#Neue Liste, in welche die Datenveränderungen abgespeichert wird
b_new = []

#Schritt 1: Multiplikation mit 100 wenn
for elem in b:
    if elem < 100:
        temp = elem*100
        b_new.append(temp)
    else:
        b_new.append(elem)
        continue

#Schritt 2: Umwandlung in String wenn Listenelement zwischen 100 und 1000
for elem in b_new:
    if elem > 100 and elem < 1000:
        index = int(elem/100)
        b_new[index]=str(elem)
    if elem >= 1000:
        for i in [i for i,x in enumerate(b_new) if x == elem]:
            del b_new[i]
            print(i)

    else:
        continue

b_new

#Frage 8 gemäss Barnaby
e = list(range(10))
e

#Multipliziere jede Nummer in dieser Liste, die kleiner ist als 100, mit 100; wenn die Nummern zwischen 100 und 1000 verwandle sie in eine String, und wenn sie grösser oder gleich 1000 ist, lösche sie.
e_neue = []
for elem in e:
    if elem > 1000:
        pass
    elif elem > 100:
        e_neue.append(str(elem))
    else:
        elem= elem *100
        e_neue.append(elem)
e_neue

e_neue = []
index = 0
for elem in e:

    if elem > 1000:
        pass

    elif elem > 100:
        e_neue.append(str(elem))
    else:
        elem = elem * 100
        e_neue.append(elem)
        print(index)
        index +=1


elem = list(range(1000))
if elem < list(range(100)):
    elem*100
elif elem < list(range(1000)):
    str(elem)
else:
    del(elem)


I am working on the file "03 Homework.ipynb".
The first task is:
9.Schreibe eine Dictionary-Liste der fünf grössten Schweizer Städte, ihrer Bevölkerung und dem jeweiligen Kanton.
Can you write Python code for it?

#Quelle: Wikipedia. Die grössten Schweizer Städte.
ZH = {'Stadt': 'Zurich', 'Bevölkerung': 396027, 'Kanton': 'ZH'}
GE = {'Stadt': 'Genf', 'Bevölkerung': 194565, 'Kanton': 'GE'}
BS = {'Stadt': 'Basel', 'Bevölkerung': 175131, 'Kanton': 'BS'}
BE = {'Stadt': 'Bern', 'Bevölkerung': 140634, 'Kanton': 'BE'}
LS = {'Stadt': 'Lausanne', 'Bevölkerung': 135629, 'Kanton': 'VD'}

dct_lst = [ZH,GE,BS,BE,LS]

dct_lst


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Challenges
Counting DNA Nucleotides

Project Rosalind is a problem set based on biotechnology concepts. It is meant to show how programming skills can help solve problems in genetics and biology.
If you have understood this section on strings, you have enough information to solve the first problem in Project Rosalind, Counting DNA Nucleotides. Give the sample problem a try.
If you get the sample problem correct, log in and try the full version of the problem!

Transcribing DNA into RNA

You also have enough information to try the second problem, Transcribing DNA into RNA. Solve the sample problem.
If you solved the sample problem, log in and try the full version!

Complementing a Strand of DNA

You guessed it, you can now try the third problem as well: Complementing a Strand of DNA. Try the sample problem, and then try the full version if you are successful.
Can you write Python code for it?

# Challenge: Counting DNA Nucleotides

# Put your code here

# Challenge: Transcribing DNA into RNA

# Put your code here

# Challenge: Complementing a Strand of DNA

# Put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Exercises
Working List

Make a list that includes four careers, such as 'programmer' and 'truck driver'.
Use the list.index() function to find the index of one career in your list.
Use the in function to show that this career is in your list.
Use the append() function to add a new career to your list.
Use the insert() function to add a new career at the beginning of the list.
Use a loop to show all the careers in your list.

Starting From Empty

Create the list you ended up with in Working List, but this time start your file with an empty list and fill it up using append() statements.
Print a statement that tells us what the first career you thought of was.
Print a statement that tells us what the last career you thought of was.

Ordered Working List

Start with the list you created in Working List.
You are going to print out the list in a number of different orders.
Each time you print the list, use a for loop rather than printing the raw list.
Print a message each time telling us what order we should see the list in.
Print the list in its original order.
Print the list in alphabetical order.
Print the list in its original order.
Print the list in reverse alphabetical order.
Print the list in its original order.
Print the list in the reverse order from what it started.
Print the list in its original order
Permanently sort the list in alphabetical order, and then print it out.
Permanently sort the list in reverse alphabetical order, and then print it out.

Ordered Numbers

Make a list of 5 numbers, in a random order.
You are going to print out the list in a number of different orders.
Each time you print the list, use a for loop rather than printing the raw list.
Print a message each time telling us what order we should see the list in.
Print the numbers in the original order.
Print the numbers in increasing order.
Print the numbers in the original order.
Print the numbers in decreasing order.
Print the numbers in their original order.
Print the numbers in the...
Can you write Python code for it?

# Ex 3.7 : Working List

# put your code here

# Ex 3.8 : Starting From Empty

# put your code here

# Ex 3.9 : Ordered Working List

# put your code here

# Ex 3.10 : Ordered Numbers

# put your code here

# Ex 3.11 : List Lengths

# put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Exercises
Famous People

Make a list that includes the names of four famous people.
Remove each person from the list, one at a time, using each of the four methods we have just seen:
Pop the last item from the list, and pop any item except the last item.
Remove one item by its position, and one item by its value.

Print out a message that there are no famous people left in your list, and print your list to prove that it is empty.
Can you write Python code for it?

# Ex 3.12 : Famous People
fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']
#Remove each person from the list, one at a time, using each of the four methods we have just seen
fpeople.remove('taylor swift')
print(fpeople)
del fpeople[2]
print(fpeople)
bowie=fpeople.pop(0)
print(bowie,fpeople)
last=fpeople.pop()
print('there are no more famous people in the list')
print(fpeople)
# put your code here

#Pop the last item from the list
fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']
fpeople.pop()
print(fpeople)
# and pop any item except the last item.
fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']
for _ in range(0,len(fpeople)-1):
    fpeople.pop(0)
print(fpeople)

fpeople = ['david bowie', 'robert plant', 'obama', 'taylor swift']
fpeople.remove('obama')
del fpeople[2]
print(fpeople)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Exercises
Alphabet Slices

Store the first ten letters of the alphabet in a list.
Use a slice to print out the first three letters of the alphabet.
Use a slice to print out any three letters from the middle of your list.
Use a slice to print out the letters from any point in the middle of your list, to the end.

Protected List

Your goal in this exercise is to prove that copying a list protects the original list.
Make a list with three people's names in it.
Use a slice to make a copy of the entire list.
Add at least two new names to the new copy of the list.
Make a loop that prints out all of the names in the original list, along with a message that this is the original list.
Make a loop that prints out all of the names in the copied list, along with a message that this is the copied list.
Can you write Python code for it?

from string import ascii_lowercase
print(ascii_lowercase)
tenletters=ascii_lowercase[0:10]
print(tenletters)

# Ex 3.13 : Alphabet Slices
#Store the first ten letters of the alphabet in a list.
alphabet=tenletters[:]
#Use a slice to print out the first three letters of the alphabet.
print(alphabet[:3])
#Use a slice to print out any three letters from the middle of your list.
print(alphabet[6:9])
#Use a slice to print out the letters from any point in the middle of your list, to the end.
print(alphabet[6:])
# put your code here

# Ex 3.14 : Protected List
#Your goal in this exercise is to prove that copying a list protects the original list.
#Make a list with three people's names in it.
names=['alice','anna','ada']
#Use a slice to make a copy of the entire list.
copied_names=names[:]
#Add at least two new names to the new copy of the list.
copied_names.append('agata')
copied_names.append('aurora')
#Make a loop that prints out all of the names in the original list, along with a message that this is the original list.
print('This is the original list:')
for name in names:
    print(name.title())
#Make a loop that prints out all of the names in the copied list, along with a message that this is the copied list.
print('This is the copy: ')
for cname in copied_names:
    print(cname.title())
print(copied_names)

#title the names in the original list
print (names)
copied_names = [i.title() for i in copied_names]
print(copied_names)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Finding an element in a list
If you want to find out the position of an element in a list, you can use the index() function.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

print(dogs.index('australian cattle dog'))


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Finding the length of a list
You can find the length of a list using the len() function.
Can you write Python code for it?

usernames = ['bernice', 'cody', 'aaron']
user_count = len(usernames)

print(user_count)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Naming and defining a list
Since lists are collection of objects, it is good practice to give them a plural name. If each item in your list is a car, call the list 'cars'. If each item is a dog, call your list 'dogs'. This gives you a straightforward way to refer to the entire list ('dogs'), and to a single item in the list ('dog').
In Python, square brackets designate a list. To define a list, you give the name of the list, the equals sign, and the values you want to include in your list within square brackets.
Can you write Python code for it?

dogs = ['border collie',
        'australian cattle dog',
        'labrador retriever']


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
The range() function
This works, but it is not very efficient if we want to work with a large set of numbers. The range() function helps us generate long lists of numbers. Here are two ways to do the same thing, using the range function.
Can you write Python code for it?

# Print the first ten numbers.
for number in range(1,11):
    print(number)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Replacing substrings
You can use the replace() function to replace any substring with another substring. To use the replace() function, give the substring you want to replace, and then the substring you want to replace it with. You also need to store the new string, either in the same string variable or in a new variable.
Can you write Python code for it?

message = "I like cats and dogs, but I'd much rather own a dog."
message = message.replace('dog', 'snake')
print(message)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Testing whether an item is in a list
You can test whether an item is in a list using the "in" keyword. This will become more useful after learning how to use if-else statements.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

print('australian cattle dog' in dogs)
print('poodle' in dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
A common looping error
One common looping error occurs when instead of using the single variable dog inside the loop, we accidentally use the variable that holds the entire list:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

for dog in dogs:
    print(dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Accessing the last items in a list
You can probably see that to get the last item in this list, we would use an index of 2. This works, but it would only work because our list has exactly three items. To get the last item in a list, no matter how long the list is, you can use an index of -1.
Can you write Python code for it?


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Here's how we might think of doing the same thing, using a list comprehension:
evens = [multiply each number by 2, for each number in the range 1-10]
Here is the same line in code:
Can you write Python code for it?

# Make a list of the first ten even numbers.
evens = [number*2 for number in range(1,11)]

for even in evens:
    print(even)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
I like this approach of using the plus sign to build strings because it is fairly intuitive. We can see that we are adding several smaller strings together to make one longer string. This is intuitive, but it is a lot of typing. There is a shorter way to do this, using placeholders.
Python ignores most of the characters we put inside of strings. There are a few characters that Python pays attention to, as we saw with strings such as "\t" and "\n". Python also pays attention to "%s" and "%d". These are placeholders. When Python sees the "%s" placeholder, it looks ahead and pulls in the first argument after the % sign:
Can you write Python code for it?

animal = 'dog'
print("I have a %s." % animal)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
If we don't change the order in our list, we can use the list to figure out who our oldest and newest users are.
Can you write Python code for it?

# Create an empty list to hold our users.
usernames = []

# Add some users.
usernames.append('bernice')
usernames.append('cody')
usernames.append('aaron')

# Greet all of our users.
for username in usernames:
    print("Welcome, " + username.title() + '!')

# Recognize our first user, and welcome our newest user.
print("\nThank you for being our very first user, " + usernames[0].title() + '!')
print("And a warm welcome to our newest user, " + usernames[-1].title() + '!')


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
If you have more than one value to put into the string you are composing, you have to pack the values into a tuple:
Can you write Python code for it?

animals = ['dog', 'cat', 'bear']
print("I have a %s, a %s, and a %s." % (animals[0], animals[1], animals[2]))


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
If you try to add something to a tuple, you will get an error:
Can you write Python code for it?

colors = ('red', 'green', 'blue')
colors.append('purple')


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
If you want to find the last appearance of a substring, you can use the rfind() function:
Can you write Python code for it?

message = "I like cats and dogs, but I'd much rather own a dog."
last_dog_index = message.rfind('dog')
print(last_dog_index)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
If you want to know where a substring appears in a string, you can use the find() method. The find() method tells you the index at which the substring begins.
Can you write Python code for it?

message = "I like cats and dogs."
dog_index = message.find('dog')
print(dog_index)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
In this example, instead of printing each dog in the list, we print the entire list every time we go through the loop. Python puts each individual item in the list into the variable dog, but we never use that variable. Sometimes you will just get an error if you try to do this:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

for dog in dogs:
    print('I like ' + dogs + 's.')


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Inserting items into a list
We can also insert items anywhere we want in a list, using the insert() function. We specify the position we want the item to have, and everything from that point on is shifted one position to the right. In other words, the index of every item after the new item is increased by one.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']
dogs.insert(1, 'poodle')

print(dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
It should be pretty clear that this code is more efficient than our previous approach, but it may not be clear what is happening. Let's take a look at everything that is happening in that first line:
We define a list called squares.
Look at the second part of what's in square brackets:
for number in range(1,11)

This sets up a loop that goes through the numbers 1-10, storing each value in the variable number. Now we can see what happens to each number in the loop:
number**2

Each number is raised to the second power, and this is the value that is stored in the list we defined. We might read this line in the following way:
squares = [raise number to the second power, for each number in the range 1-10]
Another example
It is probably helpful to see a few more examples of how comprehensions can be used. Let's try to make the first ten even numbers, the longer way:
Can you write Python code for it?

# Make an empty list that will hold the even numbers.
evens = []

# Loop through the numbers 1-10, double each one, and add it to our list.
for number in range(1,11):
    evens.append(number*2)

# Show that our list is correct:
for even in evens:
    print(even)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Just for clarification, look at how much longer the code is if you use concatenation instead of string formatting:
Can you write Python code for it?

numbers = [7, 23, 42]
print("My favorite numbers are " + str(numbers[0]) + ", " + str(numbers[1]) + ", and " + str(numbers[2]) + ".")


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
List comprehensions allow us to collapse the first three lines of code into one line. Here's what it looks like:
Can you write Python code for it?

# Store the first ten square numbers in a list.
squares = [number**2 for number in range(1,11)]

# Show that our list is correct.
for square in squares:
    print(square)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Note that reverse is permanent, although you could follow up with another call to reverse() and get back the original order of the list.
Sorting a numerical list
All of the sorting functions work for numerical lists as well.
Can you write Python code for it?

numbers = [1, 3, 4, 2]

# sort() puts numbers in increasing order.
numbers.sort()
print(numbers)

# sort(reverse=True) puts numbers in decreasing order.
numbers.sort(reverse=True)
print(numbers)

numbers = [1, 3, 4, 2]

# sorted() preserves the original order of the list:
print(sorted(numbers))
print(numbers)

numbers = [1, 3, 4, 2]

# The reverse() function also works for numerical lists.
numbers.reverse()
print(numbers)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Note that the code welcoming our newest user will always work, because we have used the index -1. If we had used the index 2 we would always get the third user, even as our list of users grows and grows.
Sorting a List
We can sort a list alphabetically, in either order.
Can you write Python code for it?

students = ['bernice', 'aaron', 'cody']

# Put students in alphabetical order.
students.sort()

# Display the list in its current order.
print("Our students are currently in alphabetical order.")
for student in students:
    print(student.title())

#Put students in reverse alphabetical order.
students.sort(reverse=True)

# Display the list in its current order.
print("\nOur students are now in reverse alphabetical order.")
for student in students:
    print(student.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Note, however, that this function only returns the index of the first appearance of the substring you are looking for. If the substring appears more than once, you will miss the other substrings.
Can you write Python code for it?

message = "I like cats and dogs, but I'd much rather own a dog."
dog_index = message.find('dog')
print(dog_index)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Notice that in this case, the spaces are also ignored. It is a good idea to test the output of the split() function and make sure it is doing what you want with the data you are interested in.
One use of this is to work with spreadsheet data in your Python programs. Most spreadsheet applications allow you to dump your data into a comma-separated text file. You can read this file into your Python program, or even copy and paste from the text file into your program file, and then turn the data into a list. You can then process your spreadsheet data using a for loop.
Other string methods
There are a number of other string methods that we won't go into right here, but you might want to take a look at them. Most of these methods should make sense to you at this point. You might not have use for any of them right now, but it is good to know what you can do with strings. This way you will have a sense of how to solve certain problems, even if it means referring back to the list of methods to remind yourself how to write the correct syntax when you need it.
Exercises
Listing a Sentence

Store a single sentence in a variable. Use a for loop to print each character from your sentence on a separate line.

Sentence List

Store a single sentence in a variable. Create a list from your sentence. Print your raw list (don't use a loop, just print the list).

Sentence Slices

Store a sentence in a variable. Using slices, print out the first five characters, any five consecutive characters from the middle of the sentence, and the last five characters of the sentence.

Finding Python

Store a sentence in a variable, making sure you use the word Python at least twice in the sentence.
Use the in keyword to prove that the word Python is actually in the sentence.
Use the find() function to show where the word Python first appears in the sentence.
Use the rfind() function to show the last place Python appears in the sentence.
Use the count() function to show...
Can you write Python code for it?

# Ex 3.22 : Listing a Sentence

# put your code here

# Ex 3.23 : Sentence List

# put your code here

# Ex 3.24 : Sentence Slices

# put your code here

# Ex 3.25 : Finding Python

# put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Notice that the last line only runs once, after the loop is completed. Also notice the use of newlines ("\n") to make the output easier to read.
top
Enumerating a list
When you are looping through a list, you may want to know the index of the current item. You could always use the list.index(value) syntax, but there is a simpler way. The enumerate() function tracks the index of each item for you, as it loops through the list:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

print("Results for the dog show are as follows:\n")
for index, dog in enumerate(dogs):
    place = str(index)
    print("Place: " + place + " Dog: " + dog.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Notice that the punctuation is left in the substrings.
It is more common to split strings that are really lists, separated by something like a comma. The split() function gives you an easy way to turn comma-separated strings, which you can't do much with in Python, into lists. Once you have your data in a list, you can work with it in much more powerful ways.
Can you write Python code for it?

animals = "dog, cat, tiger, mouse, liger, bear"

# Rewrite the string as a list, and store it in the same variable
animals = animals.split(',')
print(animals)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Python knows that you could be talking about the value 23, or the characters '23'. So it throws an error, forcing us to clarify that we want Python to treat the number as a string. We do this by casting the number into a string using the str() function:
Can you write Python code for it?

number = 23
print("My favorite number is " + str(number) + ".")


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
Reversing a list
We have seen three possible orders for a list:
- The original order in which the list was created
- Alphabetical order
- Reverse alphabetical order
There is one more order we can use, and that is the reverse of the original order of the list. The reverse() function gives us this order.
Can you write Python code for it?

students = ['bernice', 'aaron', 'cody']
students.reverse()

print(students)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
String formatting with numbers
If you recall, printing a number with a string can cause an error:
Can you write Python code for it?

number = 23
print("My favorite number is " + number + ".")


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
The FOR (iteration) loop
The for loop statement is the most widely used iteration mechanisms in Python.

Almost every structure in Python can be iterated (element by element) by a for loop

a list, a tuple, a dictionary, $\ldots$ (more details will follows)

In Python, also while loops are permitted, but for is the one you would see (and use) most of the time!

FOR Special keywords
Python allows two keywords to be used within a for loop: break and continue.
The two keywords have two different meanings:

Break used to immediatly break the loop and exit!
Continue used to skip to the next iteration step!

NOTE: The two keywords are permitted with while loops as well!
Examples
Exercises
First List - Loop

Repeat First List, but this time use a loop to print out each value in the list.

First Neat List - Loop

Repeat First Neat List, but this time use a loop to print out your statements. Make sure you are writing the same sentence for all values in your list. Loops are not effective when you are trying to generate different output for each value in your list.

Your First List - Loop

Repeat Your First List, but this time use a loop to print out your message for each item in your list. Again, if you came up with different messages for each value in your list, decide on one message to repeat for each value in your list.
Can you write Python code for it?

# Ex 3.4 : First List - Loop

# put your code here

# Ex 3.5 : First Neat List - Loop

# put your code here

# Ex 3.6 : Your First List - Loop

# put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
The format string "%d" takes care of this for us. Watch how clean this code is:
Can you write Python code for it?

number = 23
print("My favorite number is %d." % number)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
The number in parentheses is called the index of the item.
Because lists start at zero, the index of an item is always one less than its position in the list.
Because of that, Python is said to be a zero-indexed
language (as many others, like C, or Java)
So to get the second item in the list, we need to use an index of 1, and so on..
Can you write Python code for it?


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
The same kind of thing happens when you try to remove something from a tuple, or modify one of its elements. Once you define a tuple, you can be confident that its values will not change.
Using tuples to make strings
We have seen that it is pretty useful to be able to mix raw English strings with values that are stored in variables, as in the following:
Can you write Python code for it?

animal = 'dog'
print("I have a " + animal + ".")


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
There are more sophisticated ways to do string formatting in Python 3, but we will save that for later because it's a bit less intuitive than this approach. For now, you can use whichever approach consistently gets you the output that you want to see.
Exercises
Gymnast Scores

A gymnast can earn a score between 1 and 10 from each judge; nothing lower, nothing higher. All scores are integer values; there are no decimal scores from a single judge.
Store the possible scores a gymnast can earn from one judge in a tuple.
Print out the sentence, "The lowest possible score is ___, and the highest possible score is ___." Use the values from your tuple.
Print out a series of sentences, "A judge can give a gymnast ___ points."
Don't worry if your first sentence reads "A judge can give a gymnast 1 points."
However, you get 1000 bonus internet points if you can use a for loop, and have correct grammar. hint

Revision with Tuples

Choose a program you have already written that uses string concatenation.
Save the program with the same filename, but add _tuple.py to the end. For example, gymnast_scores.py becomes gymnast_scores_tuple.py.
Rewrite your string sections using %s and %d instead of concatenation.
Repeat this with two other programs you have already written.
Can you write Python code for it?

# Ex 3.26 : Gymnast Scores

# put your code here

# Ex 3.27 : Revision with Tuples

# put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
This is an example of a first-in, last-out approach. The first item in the list would be the last item processed if you kept using this approach. We will see a full implementation of this approach later on, when we learn about while loops.
You can actually pop any item you want from a list, by giving the index of the item you want to pop. So we could do a first-in, first-out approach by popping the first iem in the list:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']
first_dog = dogs.pop(0)

print(first_dog)
print(dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
This is incredibly powerful; we can now create a list of the first million numbers, just as easily as we made a list of the first ten numbers. It doesn't really make sense to print the million numbers here, but we can show that the list really does have one million items in it, and we can print the last ten items to show that the list is correct.
Can you write Python code for it?

# Store the first million numbers in a list.
numbers = list(range(1,1000001))

# Show the length of the list:
print("The list 'numbers' has " + str(len(numbers)) + " numbers in it.")

# Show the last ten numbers:
print("\nThe last ten numbers in the list are:")
for number in numbers[-10:]:
    print(number)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
This method returns a ValueError if the requested item is not in the list.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

print(dogs.index('poodle'))


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
This should make sense at this point. If it doesn't, go over the code with these thoughts in mind:
- We make an empty list called squares that will hold the values we are interested in.
- Using the range() function, we start a loop that will go through the numbers 1-10.
- Each time we pass through the loop, we find the square of the current number by raising it to the second power.
- We add this new value to our list squares.
- We go through our newly-defined list and print out each square.
Now let's make this code more efficient. We don't really need to store the new square in its own variable new_square; we can just add it directly to the list of squares. The line
new_square = number**2

is taken out, and the next line takes care of the squaring:
Can you write Python code for it?

# Store the first ten square numbers in a list.
# Make an empty list that will hold our square numbers.
squares = []

# Go through the first ten numbers, square them, and add them to our list.
for number in range(1,11):
    squares.append(number**2)

# Show that our list is correct.
for square in squares:
    print(square)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
This syntax also works for the second to last item, the third to last, and so forth.
Can you write Python code for it?


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
To enumerate a list, you need to add an index variable to hold the current index. So instead of
for dog in dogs:

You have
for index, dog in enumerate(dogs)

The value in the variable index is always an integer. If you want to print it in a string, you have to turn the integer into a string:
str(index)

The index always starts at 0, so in this example the value of place should actually be the current index, plus one:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

print("Results for the dog show are as follows:\n")
for index, dog in enumerate(dogs):
    place = str(index + 1)
    print("Place: " + place + " Dog: " + dog.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
To use a comprehension in this code, we want to write something like this:
great_students = [add 'the great' to each student, for each student in the list of students]
Here's what it looks like:
Can you write Python code for it?

# Consider some students.
students = ['bernice', 'aaron', 'cody']

# Let's turn them into great students.
great_students = [student.title() + " the great!" for student in students]

# Let's greet each great student.
for great_student in great_students:
    print("Hello, " + great_student)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
We can get any segment of a list we want, using the slice method:
Can you write Python code for it?

usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']

# Grab a batch from the middle of the list.
middle_batch = usernames[1:4]

for user in middle_batch:
    print(user.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
When we grab a slice from a list, the original list is not affected:
Can you write Python code for it?

usernames = ['bernice', 'cody', 'aaron', 'ever', 'dalia']

# Grab the first three users in the list.
first_batch = usernames[0:3]

# The original list is unaffected.
for user in usernames:
    print(user.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
You can mix string and numerical placeholders in any order you want.
Can you write Python code for it?

names = ['eric', 'ever']
numbers = [23, 2]
print("%s's favorite number is %d, and %s's favorite number is %d." % (names[0].title(), numbers[0], names[1].title(), numbers[1]))


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
sorted() vs. sort()
Whenever you consider sorting a list, keep in mind that you can not recover the original order. If you want to display a list in sorted order, but preserve the original order, you can use the sorted() function. The sorted() function also accepts the optional reverse=True argument.
Can you write Python code for it?

students = ['bernice', 'aaron', 'cody']

# Display students in alphabetical order, but keep the original order.
print("Here is the list in alphabetical order:")
for student in sorted(students):
    print(student.title())

# Display students in reverse alphabetical order, but keep the original order.
print("\nHere is the list in reverse alphabetical order:")
for student in sorted(students, reverse=True):
    print(student.title())

print("\nHere is the list in its original order:")
# Show that the list is still in its original order.
for student in students:
    print(student.title())


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Common List Operations
Modifying elements in a list
You can change the value of any element in a list if you know the position of that item.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

dogs[0] = 'australian shepherd'
print(dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Exercises
First List

Store the values 'python', 'c', and 'java' in a list. Print each of these values out, using their position in the list.

First Neat List

Store the values 'python', 'c', and 'java' in a list. Print a statement about each of these values, using their position in the list.
Your statement could simply be, 'A nice programming language is value.'

Your First List

Think of something you can store in a list. Make a list with three or four items, and then print a message that includes at least one item from your list. Your sentence could be as simple as, "One item in my list is a ____."
Can you write Python code for it?

# Ex 3.1 : First List

# put your code here

# Ex 3.2 : First Neat List

# put your code here

# Ex 3.3 : Your First List

# put your code here


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Lists and Looping
Accessing all elements in a list
This is one of the most important concepts related to lists. You can have a list with a million items in it, and in three lines of code you can write a sentence for each of those million items. If you want to understand lists, and become a competent programmer, make sure you take the time to understand this section.
We use a loop to access all the elements in a list. A loop is a block of code that repeats itself until it runs out of items to work with, or until a certain condition is met. In this case, our loop will run once for every item in our list. With a list that is three items long, our loop will run three times.
Let's take a look at how we access all the items in a list, and then try to understand how it works.
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']

for dog in dogs:
    print(dog)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Numerical Lists
There is nothing special about lists of numbers, but there are some functions you can use to make working with numerical lists more efficient. Let's make a list of the first ten numbers, and start working with it to see how we can use numbers in a list.
Can you write Python code for it?

# Print out the first ten numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in numbers:
    print(number)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Removing Items from a List
Hopefully you can see by now that lists are a dynamic structure. We can define an empty list and then fill it up as information comes into our program. To become really dynamic, we need some ways to remove items from a list when we no longer need them. You can remove items from a list through their position, or through their value.
Removing items by position
If you know the position of an item in a list, you can remove that item using the del command. To use this approach, give the command del and the name of your list, with the index of the item you want to move in square brackets:
Can you write Python code for it?

dogs = ['border collie', 'australian cattle dog', 'labrador retriever']
# Remove the first dog from the list.
del dogs[0]

print(dogs)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Sets
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Can you write Python code for it?

shapes = ['circle','square','triangle','circle']
set_of_shapes = set(shapes)
set_of_shapes

shapes = {'circle','square','triangle','circle'}
for shape in set_of_shapes:
    print(shape)

set_of_shapes.add('polygon')
print(set_of_shapes)


I am working on the file "03 List and Tuples and Sets.ipynb".
The first task is:
top
Tuples
Tuples are basically lists that can never be changed. Lists are quite dynamic; they can grow as you append and insert items, and they can shrink as you remove items. You can modify any element you want to in a list. Sometimes we like this behavior, but other times we may want to ensure that no user or no part of a program can change a list. That's what tuples are for.
Technically, lists are mutable objects and tuples are immutable objects. Mutable objects can change (think of mutations), and immutable objects can not change.
Defining tuples, and accessing elements
You define a tuple just like you define a list, except you use parentheses instead of square brackets. Once you have a tuple, you can access individual elements just like you can with a list, and you can loop through the tuple with a for loop:
Can you write Python code for it?

colors = ('red', 'green', 'blue')
print("The first color is: " + colors[0])

print("\nThe available colors are:")
for color in colors:
    print("- " + color)


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
Below is a skeleton of the SVHN data iterator for you to fill out, with notes to help along the way. The goal is an object that returns, with each call, a tuple of (X, Y) for the input and the target bounding boxes.
Can you write Python code for it?

# import some useful packages
from neon.data import NervanaDataIterator
import numpy as np
import cPickle
import os

class SVHN(NervanaDataIterator):

    def __init__(self, X, Y, lshape):

        # Load the numpy data into some variables. We divide the image by 255 to normalize the values
        # between 0 and 1.
        self.X = X / 255.
        self.Y = Y
        self.shape = lshape  # shape of the input data (e.g. for images, (C, H, W))

        # 1. assign some required and useful attributes
        self.start = 0  # start at zero
        self.ndata = ...  # number of images in X (hint: use X.shape)
        self.nfeatures = ...  # number of features in X (hint: use X.shape)

        # number of minibatches per epoch
        # to calculate this, use the batchsize, which is stored in self.be.bsz
        self.nbatches = ...

        # 2. allocate memory on the GPU for a minibatch's worth of data.
        # (e.g. use `self.be` to access the backend.). See the backend documentation.
        # to get the minibatch size, use self.be.bsz
        # hint: X should have shape (# features, mini-batch size)
        # hint: use some of the attributes previously defined above
        self.dev_X = ...
        self.dev_Y = ...

    def reset(self):
        self.start = 0

    def __iter__(self):
        # 3. loop through minibatches in the dataset
        for index in range(self.start, self.ndata, self.be.bsz):
            # 3a. grab the right slice from the numpy arrays
            inputs = ...
            targets = ...

            # The arrays X and Y data are in shape (batch_size, num_features),
            # but the iterator needs to return data with shape (num_features, batch_size).
            # here we transpose the data, and then store it as a contiguous array.
            # numpy arrays need to be contiguous before being loaded onto the GPU.
            inputs = np.ascontiguousarray(inputs.T)
            targets = np.ascontiguousarray(targets.T)

       ...


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
Below we plot the cost data over time to help you visualize the training progress. This is similiar to using the nvis command line tool to generate plots.
Can you write Python code for it?

from neon.visualizations.figure import cost_fig, hist_fig, deconv_summary_page
from neon.visualizations.data import h5_cost_data, h5_hist_data, h5_deconv_data
from bokeh.plotting import output_notebook, show

cost_data = h5_cost_data('data.h5', False)
output_notebook()
show(cost_fig(cost_data, 300, 600, epoch_axis=False))


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
If all goes well, you are ready to try training on this network! First, let's reset the dataset to zero (since you drew one example from above). We also add a test set for evaluation.
Can you write Python code for it?

train_set.reset()

# generate test set
test_set = SVHN(X=svhn['X_test'], Y=svhn['y_test'], lshape=(3, 64, 64))


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
Our ground truth box T and the model prediction y are both arrays of size (4, batch_size). We can plot an image below. Feel free to modify i to check performance on various test images. Red boxes are the model's guess, and blue boxes are the ground truth boxes.
Can you write Python code for it?

plt.figure(2)
imgs_to_plot = [0, 1, 2, 3]
for i in imgs_to_plot:
    plt.subplot(2, 2, i+1)

    title = "test {}".format(i)
    plt.imshow(X.get()[:, i].reshape(3, 64, 64).transpose(1, 2, 0))
    ax = plt.gca()
    ax.add_patch(plt.Rectangle((y[0,i], y[1,i]), y[2,i], y[3,i], fill=False, edgecolor="red")) # model guess
    ax.add_patch(plt.Rectangle((T[0,i], T[1,i]), T[2,i], T[3,i], fill=False, edgecolor="blue")) # ground truth
    plt.title(title)
    plt.axis('off')

i=0
print "Target box had coordinates: {}".format(T[:,i])
print "Model prediction has coordinates: {}".format(y[:, i])


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
The modified SVHN dataset can be found at: https://s3-us-west-1.amazonaws.com/nervana-course/svhn_64.p. Place this dataset into the data/ folder and we can then load the pickle file with our SVHN dataset.
Can you write Python code for it?

import cPickle

fileName = 'data/svhn_64.p'
print("Loading {}...".format(fileName))

with open(fileName) as f:
    svhn = cPickle.load(f)


I am working on the file "03 Writing your own dataset.ipynb".
The first task is:
To understand how the network performed, we sample images and plot the network's predicted bounding box against the ground truth bounding box. We evaluate this on the test_set, which was not used to train the network.
Can you write Python code for it?

%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt

# get a minibatch's worth of
# inputs (X) and targets (T)
iterator = test_set.__iter__()
(X, T) = iterator.next()

# fprop the input to get the model output
y = mlp.fprop(X)

# transfer from device to numpy arrays
y = y.get()
T = T.get()


I am working on the file "03 intro python II/01 Python II .ipynb".
The first task is:
2 Viel mächtigere Funktion: Modules und Libraries
Modules & Libraries
Can you write Python code for it?

import urllib
import requests
import glob
import pandas
from bs4 import BeautifulSoup
import re
#etc. etc.

def sort(string):
    elem = input('Bitte geben Sie den Suchbegriff ein: ')
    if elem in string:
        return 'Treffer'
    else:
        return 'Kein Treffer'

string_test = "«Guten Tag, ich bin der, der Sie vor einer Stunde geweckt hat», sagte der Moderator des Podiums in Stockholm, als er am Montagmittag den US-Wissenschaftler Richard H. Thaler anrief. Für seine Erforschung der Psychologie hinter wirtschaftlichen Entscheidungen bekommt dieser den Nobelpreis für Wirtschaft. Das gab die Königlich-Schwedische Wissenschaftsakademie bekannt. Der 72-Jährige lehrt an der Universität Chicago. Der Verhaltensökonom habe gezeigt, dass begrenzte Rationalität, soziale."

string_test

def suche(elem, string):
    #elem = input('Bitte geben Sie den Suchbegriff ein: ')
    if elem in string:
        return 'Treffer'
    else:
        return 'Kein Treffer'

suche(strings[1], string_test)

strings = ['Stockholm', 'blödes Wort', 'Rationalität', 'soziale']

for st in strings:
    ergebnis = suche(st, string_test)
    print(st, ergebnis)

suche(string_test)

suche(string_test)

lst = [1,3,5]

len(lst)


I am working on the file "03 intro python II/01 Python II .ipynb".
The first task is:
3 Aber wie sind Funktion, Modules und Libraries aufgebaut?
Can you write Python code for it?

import os

#Funktioniert leider nicht mit allen Built in Functionen
os.path.split??

#Beispiel Sort
def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        i = index-1
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break
    return list

#Ganz komplexe. Wenn Du nicht mit dem Modul urllib, bzw. urlretrieve
#arbeiten könntest, müsstest Du jetzt all das eintippen.

def urlretrieve(url, filename=None, reporthook=None, data=None):
    url_type, path = splittype(url)

    with contextlib.closing(urlopen(url, data)) as fp:
        headers = fp.info()

        # Just return the local path and the "headers" for file://
        # URLs. No sense in performing a copy unless requested.
        if url_type == "file" and not filename:
            return os.path.normpath(path), headers

        # Handle temporary file setup.
        if filename:
            tfp = open(filename, 'wb')
        else:
            tfp = tempfile.NamedTemporaryFile(delete=False)
            filename = tfp.name
            _url_tempfiles.append(filename)

        with tfp:
            result = filename, headers
            bs = 1024*8
            size = -1
            read = 0
            blocknum = 0
            if "content-length" in headers:
                size = int(headers["Content-Length"])

            if reporthook:
                reporthook(blocknum, bs, size)

            while True:
                block = fp.read(bs)
                if not block:
                    break
                read += len(block)
                tfp.write(block)
                blocknum += 1
                if reporthook:
                    reporthook(blocknum, bs, size)

    if size >= 0 and read < size:
        raise ContentTooShortError(
            "retrieval incomplete: got only %i out of %i bytes"
            % (read, size), result)

    return result

import urllib.request

with...


I am working on the file "03 intro python II/01 Python II .ipynb".
The first task is:
5 Struktur und Troubleshooting

Zuerst die Imports
Dann die eigenen Funktionen
Nun der eigentliche Code
Can you write Python code for it?

print('Immer im Code verwenden, um zu wissen wo der Fehler nun ganz genau passiert.')

#Beispiel Sort
def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        print(value)
        i = index-1
        print(i)
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break
    return list

sort(lst)

lst


I am working on the file "03 intro python II/01 Python II .ipynb".
The first task is:
Und zum aufrufen packe ich meine List in Klammen ()
Can you write Python code for it?

join(lst)

string = '    ich habe ganz kalt       '

string.strip()


I am working on the file "03 intro python II/02 Python II Hausaugaben.ipynb".
The first task is:
2.Baue einen for-loop, der durch vordefinierte Zahlen-list geht, und mithilfe der eben kreierten eigenen Funktion, alle Resultate verdoppelt ausdruckt.
Can you write Python code for it?


I am working on the file "03 intro python II/02 Python II Hausaugaben.ipynb".
The first task is:
3.Entwickle einen Code, der den Nutzer nach der Länge seinem Namen fragt, und ihm dann sagt, wieviele Zeichen sein Name hat.
4.Entwickle eine Funktion mit dem Namen km_rechner, der für die untenaufgeführten automatisch die Umrechung von Meilen in km durchführt und gerundet auf eine Kommastelle anzeigt.
Can you write Python code for it?


I am working on the file "03 intro python II/02 Python II Hausaugaben.ipynb".
The first task is:
5.Wir haben in einem Dictionary mit Massen, die mit ganz unterschiedlichen Formaten daherkommen. Entwickle eine Funktion namens m_converter, die diese Formate berücksichtigt, und in Meter umwandelt.
Can you write Python code for it?

#Unsere Formate
var_first = { 'measurement': 3.4, 'scale': 'kilometer' }
var_second = { 'measurement': 9.1, 'scale': 'mile' }
var_third = { 'measurement': 2.0, 'scale': 'meter' }
var_fourth = { 'measurement': 9.0, 'scale': 'inches' }

print(m_converter(var_first))
print(m_converter(var_second))
print(m_converter(var_third))
print(m_converter(var_fourth))


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
2 Viel mächtigere Funktion: Modules und Libraries
Modules & Libraries
Can you write Python code for it?

import urllib
import requests
import glob
import pandas
import BeautifulSoup
import re
#etc. etc.

!pip install requests

!pip install glob


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
3 Aber wie sind Funktion, Modules und Libraries aufgebaut?
Can you write Python code for it?

import os

#Funktioniert leider nicht mit allen Built in Functionen
os.path.split??

#Beispiel Sort
def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        i = index-1
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break
    return list

#Ganz komplexe. Wenn Du nicht mit dem Modul urllib, bzw. urlretrieve
#arbeiten könntest, müsstest Du jetzt all das eintippen.

def urlretrieve(url, filename=None, reporthook=None, data=None):
    url_type, path = splittype(url)

    with contextlib.closing(urlopen(url, data)) as fp:
        headers = fp.info()

        # Just return the local path and the "headers" for file://
        # URLs. No sense in performing a copy unless requested.
        if url_type == "file" and not filename:
            return os.path.normpath(path), headers

        # Handle temporary file setup.
        if filename:
            tfp = open(filename, 'wb')
        else:
            tfp = tempfile.NamedTemporaryFile(delete=False)
            filename = tfp.name
            _url_tempfiles.append(filename)

        with tfp:
            result = filename, headers
            bs = 1024*8
            size = -1
            read = 0
            blocknum = 0
            if "content-length" in headers:
                size = int(headers["Content-Length"])

            if reporthook:
                reporthook(blocknum, bs, size)

            while True:
                block = fp.read(bs)
                if not block:
                    break
                read += len(block)
                tfp.write(block)
                blocknum += 1
                if reporthook:
                    reporthook(blocknum, bs, size)

    if size >= 0 and read < size:
        raise ContentTooShortError(
            "retrieval incomplete: got only %i out of %i bytes"
            % (read, size), result)

    return result


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
4 Bauen wir die eigenen Funktion
Bauen wir ganze Sätze, aus Listen von Strings
Can you write Python code for it?

lst = ['ich', 'habe', 'ganz', 'kalt']

def join(mylist):
#"join" und "mylist" sind von mir gewählte Namen.
    long_str = ''
    for elem in mylist:
        long_str = long_str + ' ' + elem
# die Anführungszeichen mit Leerschlag machen, dass es Abstände zwischen den Strings gibt, wenn diese zusammengeführt werden.
    return long_str.strip()
#".strip()" ist eine kleine Subfunktion, welche die Leerschläge am Anfang und Ende löscht.


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
5 Struktur und Troubleshooting

Zuerst die Imports
Dann die eigenen Funktionen
Nun der eigentliche Code
Can you write Python code for it?


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
Bauen wir eine simple Suche
Can you write Python code for it?

satz = "Die Unabhängigkeit der Notenbanken von der Politik gilt bisher als anerkannter Grundpfeiler der modernen Wirtschafts- und Geldpolitik in fortgeschrittenen Volkswirtschaften. Zu gross wäre sonst das Risiko, dass gewählte Politiker die Notenpresse anwerfen, wenn es ihren persönlichen Zielen gerade gelegen kommt, und dass dadurch die Stabilität des Geldes und das Vertrauen in das Zahlungsmittel untergraben wird."

satz

def find(string):
    elem = input('Bitte geben Sie den Suchbegriff ein: ')
    if elem in string:
        return 'Treffer'
    else:
        return 'Kein Treffer'

find(satz)


satz = "Die Unabhängigkeit der Notenbanken von der Politik gilt bisher als anerkannter Grundpfeiler der modernen Wirtschafts- und Geldpolitik in fortgeschrittenen Volkswirtschaften. Zu gross wäre sonst das Risiko, dass gewählte Politiker die Notenpresse anwerfen, wenn es ihren persönlichen Zielen gerade gelegen kommt, und dass dadurch die Stabilität des Geldes und das Vertrauen in das Zahlungsmittel untergraben wird."

def find(string):
    elem = input('Bitte geben Sie den Suchbegriff ein: ')
    if elem in string:
        return 'Treffer'
    else:
        return 'Kein Treffer'

find(satz)


I am working on the file "03 python II/01 Python II .ipynb".
The first task is:
Und zum aufrufen packe ich meine List in Klammen ()
Can you write Python code for it?


I am working on the file "03 python II/02 Python II Hausaugaben.ipynb".
The first task is:
2.Baue einen for-loop, der durch vordefinierte Zahlen-list geht, und mithilfe der eben kreierten eigenen Funktion, alle Resultate verdoppelt ausdruckt.
Can you write Python code for it?

lst = list(range(1,5))

for x in lst:
    x = double(x)# oder print(double(x))
    print(x)


#RaphiTipps: Algebra und Logik trennen und wissen, was eine Variable gerade für ein Typ ist.
lst = list(range(1,5))
for elem in lst:
    print(double(elem))

doubleloop(lst)

type(lst)


I am working on the file "03 python II/02 Python II Hausaugaben.ipynb".
The first task is:
3.Entwickle einen Code, der den Nutzer nach der Länge seinem Namen fragt, und ihm dann sagt, wieviele Zeichen sein Name hat.
Can you write Python code for it?

def namelenght(yourbloodyname):
    elem = input("Sag mir, wie du heisst und ich sag dir, wie viele Freund du hast: ")
    if elem in yourbloodyname:
        return(len(elem))

namelenght("Philippe")

name = input("Sags mir!: ")
print("your name has " + str(len(name)) + " letters")


def zaehle(name):
    name = input('Geben Sie Ihren Namen ein: ')
    X = len(name) #print("Dein Name hat " + str(len(name)) + " letters.")
    return X

zaehle(x)

name = input ('Geben Sie Ihren Namen ein: ')
print("Dein Name hat " + str(len(name)) + 'Buchstaben')


I am working on the file "03 python II/02 Python II Hausaugaben.ipynb".
The first task is:
4.Entwickle eine Funktion mit dem Namen km_rechner, der für die untenaufgeführten automatisch die Umrechung von Meilen in km durchführt und gerundet auf eine Kommastelle anzeigt.
Can you write Python code for it?

def km_rechner(miles):
    return (print("%.1f" % (miles*1.609344)))
#das "print" führt dazu, dass auch alle Ergebnisse angezeigt werden.

km_rechner(5)
km_rechner(123)
km_rechner(53)

km_rechner(1)

def km_rechner2(miles):
    result = ("%.1f" % (miles*1.609344))
    return result

#der km_rechner2 macht genau das gleiche. Es gibt nur den Zwischenschritt, in dem "result" noch definiert wird.
#das macht den Code übersichtlicher.


def km_rechner(Kilometer):
    Kilometer = Kilometer * 1.60934 #Kilometer = round(Kilometer * 1.60934, 1)
    K = round(Kilometer, 1)
    return K

km_rechner(5)

km_rechner(123)

km_rechner(53)


I am working on the file "03 python II/02 Python II Hausaugaben.ipynb".
The first task is:
5.Wir haben in einem Dictionary mit Massen, die mit ganz unterschiedlichen Formaten daherkommen. Entwickle eine Funktion namens m_converter, die diese Formate berücksichtigt, und in Meter umwandelt.
Can you write Python code for it?

#Unsere Formate
var_first = {'measurement': 3.4, 'scale': 'kilometer' }
var_second = {'measurement': 9.1, 'scale': 'mile' }
var_third = {'measurement': 2.0, 'scale': 'meter' }
var_fourth = {'measurement': 9.0, 'scale': 'inches' }

def m_converter(length):
    if length["scale"]=="kilometer":
        result = round(length["measurement"]*1000,1)
    elif length["scale"]=="mile":
        result = round(length["measurement"]*1609.34,1)
    elif length["scale"]=="meter":
        result = round(length["measurement"]*1,1)
    elif length["scale"]=="inches":
        result = round(length["measurement"]*0.0254,1)
    else:
        return result

print(m_converter(var_first))
print(m_converter(var_second))
print(m_converter(var_third))
print(m_converter(var_fourth))


I am working on the file "03--assoc-rules.ipynb".
The first task is:
This solution is really great, as it works hard to try to extract email addresses robustly from a file with a lot of funny formatting, while retaining the memory efficiency of line-by-line file parsing. (For instance, messages where each line of the body is trimmed at a fixed column and ends with an = character, so the above code considers pairs of lines and concatenates them.)
But in a sense, we actually made the problem harder for you than necessary!
For instance, the email archive we provided is actually a subset of the full Enron email archive, which is available here. (Warning: The full archive is $\approx$ 423 MiB compressed.) In the full archive, every email is in its own file, which means it is more conceivable to assume you can read one whole message into main memory for subsequent processing.
Moreover, we didn't say what the real application might be. For example, suppose what you are mining is who corresponds with whom most frequently. In that case, you don't need to parse the whole message body; you just need to inspect the From: ... and To: ... headers in each email message.
So, for the sake of variety, let's consider a different solution that exploits the above simplifications, i.e., one email per file and from/to headers. This scenario will allow us to introduce a couple other useful Python modules: the os module, which has some portable file and directory manipulation utilities, and the email module, which helps you parse email messages. We'll just show you some code, below; you should read it and compare it against the online documentation for these modules.

Note: To run this code, you will need to download the Enron email database. For testing purposes, you can use a smaller subset that we have prepared: http://cse6040.gatech.edu/fa15/enron-maildir-subset.zip
Can you write Python code for it?

import os
from email.parser import Parser
import re

def getAllFilePaths (root_dirname):
    """Returns a list of all file paths from a given root directory."""
    AllPaths = []
    for base, Dirs, Files in os.walk (root_dirname):
        for filename in Files:
            filepath = os.path.join (base, filename)
            AllPaths.append (filepath)
    return AllPaths

# A regex object to recognize an email address:
EMAIL_PATTERN = re.compile (r'[\w.-]+@[\w.-]+')

def getCommunicators (email_msg):
    """Given an email message object, returns the sender and recipients."""
    Comms = []
    Comms.extend (EMAIL_PATTERN.findall (email_msg['From']))
    if email_msg.has_key ('To'):
        Comms.extend (EMAIL_PATTERN.findall (email_msg['To']))
    return Comms

# Main loop
EmailFilenames = getAllFilePaths ('./enron-maildir-subset')
UniqueAddresses = set () # Stores unique sender/recipient email addresses
for email_filename in EmailFilenames:
    email_file = open (email_filename)
    msg = Parser ().parse (email_file)
    email_file.close ()
    Addresses = getCommunicators (msg)
    UniqueAddresses.update (Addresses)
print (len (UniqueAddresses))


I am working on the file "03-Age_of_the_pilots.ipynb".
The first task is:
Age distribution of pilots who have had an accident
Can you write Python code for it?

flight_crew.crew_age.plot(kind='box');

age_bins = np.arange(14, 85, 5)
flight_crew['crew_age'].hist(bins=age_bins, ec='white', grid=False)
plt.xlabel('age')
plt.ylabel('number of accidents');


I am working on the file "03-Age_of_the_pilots.ipynb".
The first task is:
Number of licenses per age
Active FAA Pilot Certificates Held by Category and Age Group of Holder  according to GAMMA databook
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
As you can see, the use multiple indexing on the nested list is also possible.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
Built-in list methods
Finding the length of a list with the len() function.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
Indexing can also be done in reverse order. It goes on like n-1, n-2, n-3, ..., n-n. But, note how nice is Python, it lets you drop the n.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
Inserting at the end of a list is equivalent to call the .append method.
Can you write Python code for it?

a.insert(len(a), 'y')  # This is equivalent to call a.append('y')
print(a)


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
Please uncomment the line below to see the full docummentation for the list type.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
Slicing
Indexing a list can access a single item at a time. Slicing, on the other hand, makes possible accessing a sequence of data inside the list.
Can you write Python code for it?

a = [0, 11, 22, 33, 44, 55, 66, 77, 88, 99]

a[:4]  # The first four items

a[4:]  # All items after the first four

a[0::2]  # From index 0 up to the end with a step of 2

a[1::2]  # From index 1 up to the end with a step of 2

a[2:8:2]  # From index 2 up to index 8 (not included) with a step of 2

a[3:9:2]  # From index 3 up to index 9 (not included) with a step of 2

a[8::-2]  # Like a[0::2] but in reverse order --> a[0::2][::-1]

a[9::-2]  # Like a[1::2] but in reverse order --> a[1::2][::-1]

a[6:0:-2]  # Like a[2:8:2] but in reverse order --> a[2:8:2][::-1]

a[7:1:-2]  # Like a[3:9:2] but in reverse order --> a[3:9:2][::-1]


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The * operator can be used to repeat the elements of a base list by N times.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The + operator can be used to concatenate lists.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .clear() method removes all items from the list.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .copy() method makes a shallow copy of the list.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .index() method return the first index of the value.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .pop() method remove and return the item at a given index (by default it will pop the last item if you don't give an index).
Can you write Python code for it?

print(a.pop(2), a)

print(a.pop(4), a)

print(a.pop(), a)


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .remove() method is used to remove first occurrence of value.
Can you write Python code for it?


I am working on the file "03-BuiltinDataStructures.ipynb".
The first task is:
The .reverse() method is used to reverse the order of items in place.
Can you write Python code for it?

a.reverse()
print(a)

a.reverse()
print(a)