I am working on the file "Notebooks/switchiness_screen.ipynb".
The first task is:
I am pulling Ribosome as the top hit because it has the largest effect size of a few very significant gene sets.
Can you write Python code for it?

p = gs2['KEGG_RIBOSOME']
fig, axs = subplots(2,2, figsize=(8,6), sharex=True)
axs = axs.flatten()
violin_plot_pandas(p, dx_rna.frac, ax=axs[0])
violin_plot_pandas(p, pcna_corr, ax=axs[2])
violin_plot_pandas(p, f_win, ax=axs[1])
violin_plot_pandas(p, pcna_win, ax=axs[3])
for ax in axs:
    prettify_ax(ax)
fig.tight_layout()

fig, ax = subplots()
series_scatter(pcna_corr.ix[ti(p==0)], dx_rna.frac, color='grey',
               s=10, alpha=.1, ax=ax, ann=None)
series_scatter(pcna_corr.ix[ti(p>0)], dx_rna.frac, color=colors[0], ax=ax,
               alpha=1, s=20, ann=None)

p = gs2['KEGG_LYSOSOME']
fig, axs = subplots(2,2, figsize=(8,6), sharex=True)
axs = axs.flatten()
violin_plot_pandas(p, dx_rna.frac, ax=axs[0])
violin_plot_pandas(p, pcna_corr, ax=axs[2])
violin_plot_pandas(p, f_win, ax=axs[1])
violin_plot_pandas(p, pcna_win, ax=axs[3])
for ax in axs:
    prettify_ax(ax)
fig.tight_layout()

p = gs2['REACTOME_PACKAGING_OF_TELOMERE_ENDS']
fig, axs = subplots(2,2, figsize=(8,6), sharex=True)
axs = axs.flatten()
violin_plot_pandas(p, dx_rna.frac, ax=axs[0])
violin_plot_pandas(p, pcna_corr, ax=axs[2])
violin_plot_pandas(p, f_win, ax=axs[1])
violin_plot_pandas(p, pcna_win, ax=axs[3])
for ax in axs:
    prettify_ax(ax)
fig.tight_layout()

fig, ax = subplots()
series_scatter(pcna_corr.ix[ti(p==0)], dx_rna.frac, color='grey',
               s=10, alpha=.1, ax=ax, ann=None)
series_scatter(pcna_corr.ix[ti(p>0)], dx_rna.frac, color=colors[0], ax=ax,
               alpha=1, s=20, ann=None)

p = gs2['KEGG_FATTY_ACID_METABOLISM']
fig, axs = subplots(2,2, figsize=(8,6), sharex=True)
axs = axs.flatten()
violin_plot_pandas(p, dx_rna.frac, ax=axs[0])
violin_plot_pandas(p, pcna_corr, ax=axs[2])
violin_plot_pandas(p, f_win, ax=axs[1])
violin_plot_pandas(p, pcna_win, ax=axs[3])
for ax in axs:
    prettify_ax(ax)
fig.tight_layout()

fig, ax = subplots()
series_scatter(pcna_corr.ix[ti(p==0)], dx_rna.frac, color='grey',
               s=10, alpha=.1, ax=ax, ann=None)
series_scatter(pcna_corr.ix[ti(p>0)], dx_rna.frac,...


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
Converting Data into Tensors

When building a TF.Learn model, the input data is specified by means of an Input Builder function. This builder function will not be called until it is later passed to TF.Learn methods such as fit and evaluate. The purpose of this function is to construct the input data, which is represented in the form of Tensors or SparseTensors.
Note that input_fn will be called while constructing the TensorFlow graph, not while running the graph. What it is returning is a representation of the input data as the fundamental unit of TensorFlow computations, a Tensor (or SparseTensor).

More detail on input_fn.
Can you write Python code for it?

# Converting Data into Tensors
def input_fn(df, training = True):
    # Creates a dictionary mapping from each continuous feature column name (k) to
    # the values of that column stored in a constant Tensor.
    continuous_cols = {k: tf.constant(df[k].values)
                       for k in continuous_features}

    # Creates a dictionary mapping from each categorical feature column name (k)
    # to the values of that column stored in a tf.SparseTensor.
    # categorical_cols = {k: tf.SparseTensor(
    #     indices=[[i, 0] for i in range(df[k].size)],
    #     values=df[k].values,
    #     shape=[df[k].size, 1])
    #     for k in categorical_features}

    # Merges the two dictionaries into one.
    feature_cols = continuous_cols
    # feature_cols = dict(list(continuous_cols.items()) + list(categorical_cols.items()))

    if training:
        # Converts the label column into a constant Tensor.
        label = tf.constant(df[LABEL_COLUMN].values)

        # Returns the feature columns and the label.
        return feature_cols, label

    # Returns the feature columns
    return feature_cols

def train_input_fn():
    return input_fn(train_df, training=True)

def eval_input_fn():
    return input_fn(evaluate_df, training=False)

def test_input_fn():
    return input_fn(test_df, training=False)


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
Defining The Regression Model
Following is the simple DNNRegressor model. More detail about hidden_units, etc can be found here.
model_dir is used to save and restore our model. This is because once we have trained the model we don't want to train it again, if we only want to predict on new data-set.
Can you write Python code for it?

config = tf.contrib.learn.RunConfig(tf_random_seed=42) # not shown in the config

n_inputs  = features_scaled.shape[0]
n_features= features_scaled.shape[1]

n_inputs  = x_train.shape[0]
n_features= x_train.shape[1]
n_inputs, n_features

n_hidden1 = n_features
n_hidden2 = n_features
n_hidden3 = n_features
n_outputs = n_inputs   # because: regression

reset_graph()

with tf.name_scope('data'):
    X   = tf.placeholder(tf.float32, shape=(None, n_features), name="X")
    y   = tf.placeholder(tf.float32, shape=(None), name="y")
    unc = tf.placeholder(tf.float32, shape=(None), name="unc")

training = tf.placeholder_with_default(False, shape=(), name='training')

l1_reg       = 0.001
l2_reg       = 0.0001
dropout_rate = 0.5  # == 1 - keep_prob

X_bnorm= tf.layers.batch_normalization(X)
X_drop = tf.layers.dropout(X_bnorm, dropout_rate, training=training)

with tf.name_scope("dnn"):
    he_init      = tf.contrib.layers.variance_scaling_initializer()

    hidden1      = tf.layers.dense(X_drop , n_hidden1, name="hidden1",
                        activation=tf.nn.elu, kernel_initializer=he_init,
                        kernel_regularizer=tf.contrib.layers.l1_l2_regularizer(scale_l1=l1_reg, scale_l2=l2_reg))

    hidden1_bnorm= tf.layers.batch_normalization(hidden1, training=training, momentum=0.9)
    hidden1_drop = tf.layers.dropout(hidden1_bnorm, dropout_rate, training=training)

    hidden2      = tf.layers.dense(hidden1_drop, n_hidden2, name="hidden2",
                        activation=tf.nn.elu, kernel_initializer=he_init,
                        kernel_regularizer=tf.contrib.layers.l1_l2_regularizer(scale_l1=l1_reg, scale_l2=l2_reg))

    hidden2_bnorm= tf.layers.batch_normalization(hidden2, training=training, momentum=0.9)
    hidden2_drop = tf.layers.dropout(hidden2_bnorm, dropout_rate, training=training)

    hidden3      = tf.layers.dense(hidden2_drop, n_hidden3, name="hidden3",
                        activation=tf.nn.elu, kernel_initializer=he_init,
                       ...


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
Filtering Categorical and Continuous features
We store Categorical, Continuous and Target features names in different variables. This will be helpful in later steps.
Can you write Python code for it?

# categorical_features = [feature for feature in features if 'cat' in feature]
categorical_features  = []
continuous_features   = [feature for feature in train_df.columns]# if 'cat' in feature]
LABEL_COLUMN          = 'flux'


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
Load CSVs data
Can you write Python code for it?

nSkip = 20
spitzerDataRaw  = pd.read_csv('pmap_ch2_0p1s_x4_rmulti_s3_7.csv')

PLDpixels = pd.DataFrame({key:spitzerDataRaw[key] for key in spitzerDataRaw.columns.values if 'pix' in key})
PLDpixels

PLDnorm = np.sum(np.array(PLDpixels),axis=1)

PLDpixels = (PLDpixels.T / PLDnorm).T
PLDpixels

spitzerData = spitzerDataRaw.copy()
for key in spitzerDataRaw.columns:
    if key in PLDpixels.columns:
        spitzerData[key] = PLDpixels[key]

testPLD = np.array(pd.DataFrame({key:spitzerData[key] for key in spitzerData.columns.values if 'pix' in key}))
assert(not sum(abs(testPLD - np.array(PLDpixels))).all())
print('Confirmed that PLD Pixels have been Normalized to Spec')

notFeatures     = ['flux', 'fluxerr', 'xerr', 'yerr', 'xycov', 't_cernox']

periodMax           = spitzerData['bmjd'].values.max() - spitzerData['bmjd'].values.min()
periodMin           = np.min(np.diff(spitzerData['bmjd'].values))
spitzerData['freq'] = np.linspace(np.pi/periodMax, 4*np.pi/periodMin, spitzerData['bmjd'].values.size)

feature_columns = spitzerData.drop(notFeatures,axis=1).columns.values
features        = spitzerData.drop(notFeatures,axis=1).values
labels          = spitzerData['flux'].values

stdScaler = StandardScaler()

features_scaled = stdScaler.fit_transform(features)
labels_scaled   = labels#stdScaler.fit_transform(labels[:,None]).ravel()

idx_valtest, idx_train = train_test_split(np.arange(labels_scaled.size), test_size=0.6, random_state=42)
idx_val, idx_test      = train_test_split(idx_valtest                  , test_size=0.5, random_state=42)

x_val   = features_scaled[idx_val]
x_test  = features_scaled[idx_test]
x_train = features_scaled[idx_train]

y_val   = labels_scaled[idx_val]
y_test  = labels_scaled[idx_test]
y_train = labels_scaled[idx_train]

y_val_err   = spitzerData['fluxerr'].values[idx_val]
y_test_err  = spitzerData['fluxerr'].values[idx_test]
y_train_err = spitzerData['fluxerr'].values[idx_train]

print(x_val.shape  , 'validation samples')
print(x_train.shape, 'train samples')
print(x_test.shape , 'test...


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
Predicting output for test data
Most of the time prediction script would be separate from training script (we need not to train on same data again) but I am providing both in same script here; as I am not sure if we can create multiple notebook and somehow share data between them in Kaggle.
Can you write Python code for it?

def de_median(x):
    return x - np.median(x)

predicted_output = list(regressor.predict(input_fn=test_input_fn))
# x = list(predicted_output)

r2_score(test_df['flux'].values,predicted_output)*100

print('Full notebook took {} seconds'.format(time()-start0))


I am working on the file "Notebooks/tensorflow_CoreTF_Spitzer - ELU.ipynb".
The first task is:
We only take first 1000 rows for training/testing and last 500 row for evaluation.
This done so that this script does not consume a lot of kaggle system resources.
Can you write Python code for it?

# train_df = df_train_ori.head(1000)
# evaluate_df = df_train_ori.tail(500)

# test_df = df_test_ori.head(1000)

# MODEL_DIR = "tf_model_spitzer/withNormalization_drop50/relu"
# MODEL_DIR = "tf_model_spitzer/adamOptimizer_with_drop50/relu"
MODEL_DIR = "tf_model_spitzer/adamOptimizer/drop50/elu/"

print("train_df.shape = "   , train_df.shape)
print("test_df.shape = "    , test_df.shape)
print("evaluate_df.shape = ", evaluate_df.shape)


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
Converting Data into Tensors

When building a TF.Learn model, the input data is specified by means of an Input Builder function. This builder function will not be called until it is later passed to TF.Learn methods such as fit and evaluate. The purpose of this function is to construct the input data, which is represented in the form of Tensors or SparseTensors.
Note that input_fn will be called while constructing the TensorFlow graph, not while running the graph. What it is returning is a representation of the input data as the fundamental unit of TensorFlow computations, a Tensor (or SparseTensor).

More detail on input_fn.
Can you write Python code for it?

# Converting Data into Tensors
def input_fn(df, training = True):
    # Creates a dictionary mapping from each continuous feature column name (k) to
    # the values of that column stored in a constant Tensor.
    continuous_cols = {k: tf.constant(df[k].values)
                       for k in continuous_features}

    # Creates a dictionary mapping from each categorical feature column name (k)
    # to the values of that column stored in a tf.SparseTensor.
    # categorical_cols = {k: tf.SparseTensor(
    #     indices=[[i, 0] for i in range(df[k].size)],
    #     values=df[k].values,
    #     shape=[df[k].size, 1])
    #     for k in categorical_features}

    # Merges the two dictionaries into one.
    feature_cols = continuous_cols
    # feature_cols = dict(list(continuous_cols.items()) + list(categorical_cols.items()))

    if training:
        # Converts the label column into a constant Tensor.
        label = tf.constant(df[LABEL_COLUMN].values)

        # Returns the feature columns and the label.
        return feature_cols, label

    # Returns the feature columns
    return feature_cols

def train_input_fn():
    return input_fn(train_df, training=True)

def eval_input_fn():
    return input_fn(evaluate_df, training=True)

# def test_input_fn():
#     return input_fn(test_df.drop(LABEL_COLUMN,axis=1), training=False)

def test_input_fn():
    return input_fn(test_df, training=False)


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
Importance Sampling
Can you write Python code for it?

importances = randForest.feature_importances_
indices     = np.argsort(importances)[::-1]
std         = np.std([tree.feature_importances_ for tree in randForest.estimators_],axis=0)

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(features.shape[1]), importances[indices],
       color="r", yerr=std[indices], align="center")
plt.xticks(range(features.shape[1]), feature_columns[indices], rotation=60)
plt.xlim([-1, features.shape[1]])
plt.show()

cumsum = np.cumsum(importances[indices])
nImportantSamples = np.argmax(cumsum >= 0.95) + 1
nImportantSamples


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
NEED TO TEST NORMALIZING BEFORE OR AFTER THE TRAIN TEST SPLIT
I am pretty sure that we need to renormalize before the train test split. I wrote this part of the code before quickly, without thinking it through.
Can you write Python code for it?

x_val, x_traintest, y_val, y_traintest = train_test_split(randForest9.components_.T, labels_SSscaled, test_size=0.8, random_state=42)
x_train, x_test, y_train, y_test       = train_test_split(x_traintest, y_traintest, test_size=0.5, random_state=42)

# ReNormalization = False # leave them mean/std scaled
ReNormalization = True # min-max scale them (0-1)
if ReNormalization:
    # min-max scale it (0-1)
    x_val   = minmax_scale(x_val.astype('float32'))
    x_train = minmax_scale(x_train.astype('float32'))
    x_test  = minmax_scale(x_test.astype('float32'))

    y_val   = minmax_scale(y_val.astype('float32'))
    y_train = minmax_scale(y_train.astype('float32'))
    y_test  = minmax_scale(y_test.astype('float32'))

print(x_val.shape[0]  , 'validation samples')
print(x_train.shape[0], 'train samples')
print(x_test.shape[0] , 'test samples')

randForest_feature_columns = ['randForest' + str(k) for k in range(randForest9.explained_variance_ratio_.size)]
randForest_feature_columns

train_df    = pd.DataFrame(np.c_[x_train, y_train], columns=list(randForest_feature_columns) + ['flux'])
test_df     = pd.DataFrame(np.c_[x_test , y_test ], columns=list(randForest_feature_columns) + ['flux'])
evaluate_df = pd.DataFrame(np.c_[x_val  , y_val  ], columns=list(randForest_feature_columns) + ['flux'])

train_df.columns

[key for key in train_df.columns if 'flux' not in key]


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
PCA Pretrained Random Forest Approach
Can you write Python code for it?

from sklearn.decomposition import PCA
pca = PCA()
pca_feature_set = pca.fit_transform(features_SSscaled)

# for nComps in range(1,spitzerData.shape[1]):
randForest_PCA = RandomForestRegressor(n_estimators=1000, criterion='mse', max_depth=None, min_samples_split=2, \
                                   min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', \
                                   max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=True, \
                                   n_jobs=-1, random_state=42, verbose=0, warm_start=True)

randForest_PCA.fit(pca_feature_set, labels_SSscaled)

randForest_PCA.oob_score_


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
Predicting output for test data
Most of the time prediction script would be separate from training script (we need not to train on same data again) but I am providing both in same script here; as I am not sure if we can create multiple notebook and somehow share data between them in Kaggle.
Can you write Python code for it?

def de_median(x):
    return x - np.median(x)

predicted_output = regressor.predict(input_fn=test_input_fn)
x = list(predicted_output)

# print([predicted_output() for _ in range(10)])
plt.plot((x - np.median(x)) / np.std(x),'.',alpha=0.1);
plt.plot((test_df['flux'].values - np.median(test_df['flux'].values)) / np.std(test_df['flux'].values),'.',alpha=0.1);

plt.plot(de_median(x - test_df['flux'].values)/x,'.',alpha=0.1);
plt.ylim(-1.0,1.0);

test_df['flux'].values.size/0.4

r2_score(test_df['flux'].values,x)*100

print('Full notebook took {} seconds'.format(time()-start0))


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
Random Forest Pretrained Random Forest Approach
Can you write Python code for it?

nImportantSamples = d

rfi_feature_set = features_SSscaled[importances[indices][:nImportantSamples]]

# for nComps in range(1,spitzerData.shape[1]):
randForest_RF = RandomForestRegressor(n_estimators=1000, criterion='mse', max_depth=None, min_samples_split=2, \
                                   min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', \
                                   max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=True, \
                                   n_jobs=-1, random_state=42, verbose=0, warm_start=True)

randForest_RF.fit(rfi_feature_set, labels_SSscaled)

randForest_RF.oob_score_


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - RandomForests - relu.ipynb".
The first task is:
Random Forest Regulation Attempts
Can you write Python code for it?

# for nComps in range(1,spitzerData.shape[1]):
randForestSqrt = RandomForestRegressor(n_estimators=1000, criterion='mse', max_depth=None, min_samples_split=2, \
                                   min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='sqrt', \
                                   max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=True, \
                                   n_jobs=-1, random_state=42, verbose=0, warm_start=True)

randForestSqrt.fit(features, labels)

importancesSqrt = randForestSqrt.feature_importances_
indicesSqrt     = np.argsort(importancesSqrt)[::-1]
stdSqrt         = np.std([tree.feature_importances_ for tree in randForestSqrt.estimators_],axis=0)

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(features.shape[1]), importancesSqrt[indicesSqrt],
       color="r", yerr=stdSqrt[indicesSqrt], align="center")
plt.xticks(range(features.shape[1]), feature_columns[indicesSqrt], rotation=60)
plt.xlim([-1, features.shape[1]])
plt.show()

cumsumSqrt = np.cumsum(importancesSqrt[indicesSqrt])
dSqrt = np.argmax(cumsumSqrt >= 0.95) + 1
dSqrt

# for nComps in range(1,spitzerData.shape[1]):
randForestLog2 = RandomForestRegressor(n_estimators=1000, criterion='mse', max_depth=None, min_samples_split=2, \
                                   min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='log2', \
                                   max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=True, \
                                   n_jobs=-1, random_state=42, verbose=0, warm_start=True)

randForestLog2.fit(features, labels)

importancesLog2 = randForestLog2.feature_importances_
indicesLog2     = np.argsort(importancesLog2)[::-1]
stdLog2         = np.std([tree.feature_importances_ for tree in randForestLog2.estimators_],axis=0)

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(features.shape[1]), importancesLog2[indicesLog2],
 ...


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - SELU.ipynb".
The first task is:
Converting Data into Tensors

When building a TF.Learn model, the input data is specified by means of an Input Builder function. This builder function will not be called until it is later passed to TF.Learn methods such as fit and evaluate. The purpose of this function is to construct the input data, which is represented in the form of Tensors or SparseTensors.
Note that input_fn will be called while constructing the TensorFlow graph, not while running the graph. What it is returning is a representation of the input data as the fundamental unit of TensorFlow computations, a Tensor (or SparseTensor).

More detail on input_fn.
Can you write Python code for it?


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - SELU.ipynb".
The first task is:
Defining The Regression Model
Following is the simple DNNRegressor model. More detail about hidden_units, etc can be found here.
model_dir is used to save and restore our model. This is because once we have trained the model we don't want to train it again, if we only want to predict on new data-set.
Can you write Python code for it?

def selu(z,
         scale=1.0507009873554804934193349852946,
         alpha=1.6732632423543772848170429916717):
    return scale * tf.where(z >= 0.0, z, alpha * tf.nn.elu(z))

nHidden1  = 10
nHidden2  = 5
nHidden3  = 10

regressor = tf.contrib.learn.DNNRegressor(activation_fn=selu, dropout=0.5, optimizer=tf.train.AdamOptimizer,
    feature_columns=engineered_features, hidden_units=[nHidden1, nHidden2, nHidden3], model_dir=MODEL_DIR)


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - SELU.ipynb".
The first task is:
Filtering Categorical and Continuous features
We store Categorical, Continuous and Target features names in different variables. This will be helpful in later steps.
Can you write Python code for it?


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - SELU.ipynb".
The first task is:
Training and Evaluating Our Model
add progress bar through python logging
Can you write Python code for it?

# Training Our Model
nFitSteps = 50000
start = time()
wrap  = regressor.fit(input_fn=train_input_fn, steps=nFitSteps)
print('TF Regressor took {} seconds'.format(time()-start))

# Evaluating Our Model
print('Evaluating ...')
results = regressor.evaluate(input_fn=eval_input_fn, steps=1)

for key in sorted(results):
    print("{}: {}".format(key, results[key]))

print("Val Acc: {:.3f}".format((1-results['loss'])*100))


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - SELU.ipynb".
The first task is:
We only take first 1000 rows for training/testing and last 500 row for evaluation.
This done so that this script does not consume a lot of kaggle system resources.
Can you write Python code for it?

# train_df = df_train_ori.head(1000)
# evaluate_df = df_train_ori.tail(500)

# test_df = df_test_ori.head(1000)

# MODEL_DIR = "tf_model_spitzer/withNormalization_drop50/relu"
# MODEL_DIR = "tf_model_spitzer/adamOptimizer_with_drop50/relu"
MODEL_DIR = "tf_model_spitzer/adamOptimizer_with_drop50/selu/"

print("train_df.shape = "   , train_df.shape)
print("test_df.shape = "    , test_df.shape)
print("evaluate_df.shape = ", evaluate_df.shape)


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - relu.ipynb".
The first task is:
Converting Data into Tensors

When building a TF.Learn model, the input data is specified by means of an Input Builder function. This builder function will not be called until it is later passed to TF.Learn methods such as fit and evaluate. The purpose of this function is to construct the input data, which is represented in the form of Tensors or SparseTensors.
Note that input_fn will be called while constructing the TensorFlow graph, not while running the graph. What it is returning is a representation of the input data as the fundamental unit of TensorFlow computations, a Tensor (or SparseTensor).

More detail on input_fn.
Can you write Python code for it?


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - relu.ipynb".
The first task is:
Load CSVs data
Can you write Python code for it?

nSkip = 20
spitzerDataRaw  = pd.read_csv('pmap_ch2_0p1s_x4_rmulti_s3_7.csv')[::nSkip]

PLDpixels = pd.DataFrame({key:spitzerDataRaw[key] for key in spitzerDataRaw.columns.values if 'pix' in key})
PLDpixels

PLDnorm = np.sum(np.array(PLDpixels),axis=1)

PLDpixels = (PLDpixels.T / PLDnorm).T
PLDpixels

spitzerData = spitzerDataRaw.copy()
for key in spitzerDataRaw.columns:
    if key in PLDpixels.columns:
        spitzerData[key] = PLDpixels[key]

testPLD = np.array(pd.DataFrame({key:spitzerData[key] for key in spitzerData.columns.values if 'pix' in key}))
assert(not sum(abs(testPLD - np.array(PLDpixels))).all())
print('Confirmed that PLD Pixels have been Normalized to Spec')

notFeatures     = ['flux', 'fluxerr', 'xerr', 'yerr', 'xycov']
feature_columns = spitzerData.drop(notFeatures,axis=1).columns.values
features        = spitzerData.drop(notFeatures,axis=1).values
labels          = spitzerData['flux'].values

stdScaler = StandardScaler()

features_scaled = stdScaler.fit_transform(features)
labels_scaled   = stdScaler.fit_transform(labels[:,None]).ravel()

x_valtest, x_train, y_valtest, y_train = train_test_split(features_scaled, labels_scaled, test_size=0.6, random_state=42)
x_val, x_test, y_val, y_test           = train_test_split(x_valtest, y_valtest, test_size=0.5, random_state=42)

# x_val   = minmax_scale(x_val.astype('float32'))
# x_train = minmax_scale(x_train.astype('float32'))
# x_test  = minmax_scale(x_test.astype('float32'))

# y_val   = minmax_scale(y_val.astype('float32'))
# y_train = minmax_scale(y_train.astype('float32'))
# y_test  = minmax_scale(y_test.astype('float32'))

print(x_val.shape[0]  , 'validation samples')
print(x_train.shape[0], 'train samples')
print(x_test.shape[0] , 'test samples')

train_df    = pd.DataFrame(np.c_[x_train, y_train], columns=list(feature_columns) + ['flux'])
test_df     = pd.DataFrame(np.c_[x_test , y_test ], columns=list(feature_columns) + ['flux'])
evaluate_df = pd.DataFrame(np.c_[x_val  , y_val  ], columns=list(feature_columns) + ['flux'])


I am working on the file "Notebooks/tensorflow_DNNRegressor_Spitzer - relu.ipynb".
The first task is:
Training and Evaluating Our Model
add progress bar through python logging
Can you write Python code for it?

import logging
logging.getLogger().setLevel(logging.INFO)

# Training Our Model
nFitSteps = 100000
start = time()
wrap  = regressor.fit(input_fn=train_input_fn, steps=nFitSteps)
print('TF Regressor took {} seconds'.format(time()-start))

# Evaluating Our Model
print('Evaluating ...')
results = regressor.evaluate(input_fn=eval_input_fn, steps=1)

for key in sorted(results):
    print("{}: {}".format(key, results[key]))

print("Val Acc: {:.3f}".format((1-results['loss'])*100))


I am working on the file "Notebooks/test_DOS.ipynb".
The first task is:
DOS Computation
Can you write Python code for it?

dos_values = np.real(MY_DWAVE_MODEL.get_dos())

fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)

x_values = MY_DWAVE_MODEL.lattice.omega_mesh / T_CST
xmin = np.amin(x_values)
xmax = np.amax(x_values)

ax.set_xlim([xmin, xmax])
ax.set_xticks(np.linspace(int(xmin), int(xmax), 13,endpoint=True))

ax.plot(x_values, dos_values)


fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)

x_axis_ampl = 4.5
xmin = -x_axis_ampl
xmax = x_axis_ampl

ax.set_xlim([xmin, xmax])
#ax.set_ylim([0.0, 1.0])
l_xticks = np.linspace(int(xmin), int(xmax), 9,endpoint=True)
ax.set_xticks(l_xticks)
ax.set_xticklabels(['%1.1f'  %elem for elem in l_xticks])
#ax.set_xticklabels([r'$\psi$' for elem in l_xticks])
#ax.set_yticks(np.linspace(xmin, xmax, 5,endpoint=True))
#ax.set_yticklabels(['%1.1f'  %elem for elem in np.linspace(xmin, xmax,5,endpoint=True)])

dos_values = np.real(MY_MODEL.get_dos())

ax.plot(MY_MODEL.lattice.omega_mesh/T_CST, dos_values)


I am working on the file "Notebooks/test_DOS.ipynb".
The first task is:
MC Driver
Instantiation
Can you write Python code for it?

BCS_PARAMS = {"width":20, "use_assaad": True,
              "uniform_phase": False,  "temperature": 1.75*145.0}
MY_DWAVE_MODEL.set_params(BCS_PARAMS)
print MY_DWAVE_MODEL._uniform_phase

MC_Params = {"seed": 222315, "intervals": 100,
             "target_snapshots": 15, "observable_list":["correlation_length"]}
MY_DRIVER = MCMCDriver(MY_DWAVE_MODEL, MC_Params)


I am working on the file "Notebooks/test_DOS.ipynb".
The first task is:
Modification
Can you write Python code for it?

BCS_PARAMS = {"width":20, "use_assaad": True,
              "uniform_phase": True,  "temperature": 1.75*145.0, "delta":1.0 * T_CST}
MY_DWAVE_MODEL.set_params(BCS_PARAMS)
print MY_DWAVE_MODEL
print "temp: ", K_to_meV(MY_DWAVE_MODEL.temperature), "meV"


MC_PARAMS_MP = {"intervals": BCS_PARAMS["width"]**2 / 2,
             "target_snapshots": 25,
               "algorithm":"metropolis"}
MC_PARAMS_CLUSTER = {"intervals": 5,
             "target_snapshots": 25,
            "algorithm":"cluster"}
MY_DRIVER.set_params(MC_PARAMS_MP)
print MY_DWAVE_MODEL._uniform_phase

print MY_DRIVER
print MY_DRIVER.params

MY_DRIVER.mc_object.set_params({"temperature": 2.0 * 145.0})
MY_DRIVER.thermalize(20000)
#MY_DRIVER.mc_object.set_params({"temperature": 1.1 * 145.0})
#MY_DRIVER.thermalize(50)

MY_DRIVER.execute()

result = MY_DRIVER.result
data = result.observable_results["correlation_length"]
print data["length_values"].size
print data["correlation_values"]
print result
x_data = np.sqrt(data["length_values"])
y_data = data["correlation_values"]

fig, ax = plt.subplots(figsize = (10, 8), dpi=100, frameon=False)

ax.plot(x_data, y_data)

popt, pcov = curve_fit(func, x_data, y_data)
print popt
ax.plot(x_data, func(x_data, popt[0], popt[1], popt[2]))
print "corr length:", 1.0/popt[1]

results = pickle.load( open( "result_corr_dwave_new.txt", "rb" ) )
results = np.append(results, pickle.load( open( "result_corr_dwave_new2.txt", "rb" ) ))
#results = np.append(results, pickle.load( open( "result_corr_dwave_4.txt", "rb" ) ))
#results = np.append(results, pickle.load( open( "result_corr_dwave_5.txt", "rb" ) ))
#results = np.append(results, pickle.load( open( "result_corr_dwave_6.txt", "rb" ) ))
data = results[0].observable_results["correlation_length"]
l_values = []
for elem in data['correlation_values']:
    l_values.append(np.average(elem))
print data["length_values"].size
print len(l_values)

datas = {}
temps =np.array([])
for elem in results:
    temps = np.append(temps, elem.bcs_params['temperature'])
temps = np.unique(temps)
for temp in temps:
    datas[temp] = np.array([elem for elem in results if elem.bcs_params['temperature']==temp])
print temps
print datas[temps[0]].size

x_datas = {}
y_datas = {}

for temp in temps:
    x_datas[temp] =...


TB_PARAMS = {"width":20, "use_assaad": True}
MY_MODEL.set_params(TB_PARAMS)
print MY_MODEL


I am working on the file "Notebooks/test_DOS.ipynb".
The first task is:
d Wave
Instantiation
Can you write Python code for it?

T_CST = 0.25
BCS_PARAMS = {"width":4, "chem_potential": 0.0,
              "hopping_constant": T_CST, "J_constant":  0.1 * T_CST / 0.89,
              "g_constant": 0.25, "delta": 1.0 * T_CST, "use_assaad": True,
              "uniform_phase": True, "temperature": 100}
MY_DWAVE_MODEL = DWaveModel(BCS_PARAMS)

print MY_DWAVE_MODEL


I am working on the file "Notebooks/test_cluster.ipynb".
The first task is:
TB Model
We pick the following parameters:
+ hopping constant $ t= 250$ meV
+ $\Delta = 1.0 t$ so that $T_c^{MF} = 0.5 t$, and so that $\xi_0 \simeq a_0$
+ $g = -0.25$, unitless, so as to match the article's formalism, not the thesis'
+ $J = \dfrac{0.1 t}{0.89}$ so as to set $T_{KT} = 0.1 t$.
This means that we have the following physical properties
Can you write Python code for it?

Tc_mf = meV_to_K(0.5*250)
print meV_to_K(pi/2.0)
print 1.0/0.89
print cst.physical_constants["Boltzmann constant"]

print '$T_c^{MF} = $', Tc_mf, "K"
T_KT =  meV_to_K(0.1*250)
print r"$T_{KT} = $", T_KT, "K"


I am working on the file "Notebooks/test_cluster.ipynb".
The first task is:
d Wave
Instantiation
Can you write Python code for it?


I am working on the file "Notebooks/word2vec/sentiment_w2vec_tf.ipynb".
The first task is:
Proof of principal - ish
To test that the algorithms are worlking we run over a couple of sentences, identified by a human to be happy, scary and agry respectively.
Negative scores (i.e. the sentences average embedding vectors points in opposite direction relative to the mood) are set to 0.
Can you write Python code for it?

happy_string_ = "Even Harry, who knew nothing about the different brooms, thought it looked wonderful. Sleek and shiny, with a mahogany handle, it had a long tail of neat, straight twigs and Nimbus Two Thousand written in gold near the top. As seven o'clock drew nearer, Harry left the castle and set off in the dusk toward the Quidditch field. Held never been inside the stadium before. Hundreds of seats were raised in stands around the field so that the spectators were high enough to see what was going on. At either end of the field were three golden poles with hoops on the end. They reminded Harry of the little plastic sticks Muggle children blew bubbles through, except that they were fifty feet high. Too eager to fly again to wait for Wood, Harry mounted his broomstick and kicked off from the ground. What a feeling -- he swooped in and out of the goal posts and then sped up and down the field. The Nimbus Two Thousand turned wherever he wanted at his lightest touch."
scary_string = "and the next second, Harry felt Quirrell's hand close on his wrist. At once, a needle-sharp pain seared across Harry's scar; his head felt as though it was about to split in two; he yelled, struggling with all his might, and to his surprise, Quirrell let go of him. The pain in his head lessened -- he looked around wildly to see where Quirrell had gone, and saw him hunched in pain, looking at his fingers -- they were blistering before his eyes."
angry_string = 'He’d forgotten all about the people in cloaks until he passed a group of them next to the baker’s. He eyed them angrily as he passed. He didn’t know why, but they made him uneasy. This bunch were whispering  excitedly, too, and he couldn’t see a single collectingtin. It was on his way back past them, clutching a large doughnut in a bag, that he caught a few words of what they were saying.'

happy_string_words = re.sub(r"\p{P}+", "", happy_string_).split()
scary_string_words = re.sub(r"\p{P}+", "", scary_string).split()
angry_string_words = re.sub(r"\p{P}+",...


I am working on the file "Notebooks/word2vec/sentiment_w2vec_tf.ipynb".
The first task is:
Train the model
Run the training and return the final normalized embeddings. The model can be trained useing skipgram or continuos bag of string CBOW, controlled by a switch in the file tf_W0rd2Vec.py. Othe paramaters of the model are also hard coded in here.
Can you write Python code for it?

words = l_data.text_8(200000)
embeddings = w2v.run_embeddings()


I am working on the file "Notes/Ensemble/ID3 Decision Tree.ipynb".
The first task is:
Pandas Version
Can you write Python code for it?

import pandas as pd
import numpy as np
def CalcShannonEnt(dataSet):
    pass


I am working on the file "Notes/Regression.ipynb".
The first task is:
Underfitting
Can you write Python code for it?

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.linspace(0,4*math.pi,100)
y = map(math.sin,x)
plt.plot(x,y)
plt.plot(x,y,'o')
plt.show()


I am working on the file "Notes/conventions.ipynb".
The first task is:
All cases show agreement.
I'm not quite sure how to interpret this weird sign difference.  Flipping the signs is one of the things you do when inverting a rotation, but you also flip the order of the angles.  This could essentially be done here as well if we also flip the order of m1 and m2 — except that we need an additional factor of $(-1)^{m_1+m_2}$.  So we could think of this as saying that one of these provides the D matrix for the inverse rotation of the other, and they swap the order of the m arguments, and there's a (Condon-Shortley) phase difference.
I'll just quickly verify that Rotation.D actually satisfies this symmetry:
Can you write Python code for it?

for j in range(6):
    for m1 in range(-j, j+1):
        for m2 in range(-j, j+1):
            #print(j, m1, m2)
            difference = sympy.simplify(Rotation.D(j, m1, m2, -psi, -theta, -phi).doit()
                                        - (-1)**(m1+m2)*Rotation.D(j, m2, m1, -phi, -theta, -psi).doit())
            if difference:
                display(difference)


I am working on the file "Notes/conventions.ipynb".
The first task is:
Mathematica documentation
The Mathematica documentation for WignerD says

WignerD[{j, m_1, m_2}], psi, theta, phi] gives the Wigner D-function $D^j_{m_1, m_2}(\psi, \theta, \phi)$.

The Wigner D-function $D^j_{m_1, m_2}$ gives the matrix element of a rotation operator parametrized by Euler angles in a $2 j+1$-dimensional unitary representation of a rotation group when parameters $j, m_1, m_2$ are physical, i.e. all integers or half-integers such that $-j \leq m_1,m_2 \leq j$.

The Wolfram Language uses phase conventions where $D^j_{m_1, m_2}(\psi, \theta, \phi) = e^{i m_1 \psi + i m_2 \phi} D^j_{m_1, m_2}(0, \theta, 0)$.

WignerD[{j, m1, m2}, psi, theta, phi] == (-1)^(m1 - m2) Conjugate[WignerD[{j, -m1, -m2}, psi, theta, phi]

WignerD[{j, m1, m2}, psi, theta, phi] == (-1)^(m1 - m2) WignerD[{j, m2, m1}, phi, theta, psi]

There are no more specifics about what the Euler angles mean in this function's documentation, but the documentation for EulerMatrix[{alpha, beta, gamma}] says that it "gives the Euler 3D rotation matrix formed by rotating by $\alpha$ around the current $z$ axis, then by $\beta$ around the current $y$ axis, and then by $\gamma$ around the current $z$ axis."  This is ambiguous, but
we later find that EulerMatrix[{alpha, beta, gamma}, {a, b, c}] is equivalent to $R_{\alpha, a} R_{\beta, b} R_{\gamma, c}$.  Evidently, "current" refers to the rotating body axes, and so EulerMatrix[{alpha, beta, gamma}] is what I would write in quaternion form as
\begin{equation}
  e^{\alpha \hat{z}/2} e^{\beta \hat{y}/2} e^{\gamma \hat{z}/2} = e^{\gamma \hat{z}''/2} e^{\beta \hat{y}'/2} e^{\alpha \hat{z}/2}
\end{equation}
I've created a CSV file with the analytic expressions for j from 0 through 5, using this code:
mathematica
SetDirectory[NotebookDirectory[]];
Export[
  "conventions_mathematica.csv",
  Flatten[
   Table[{j, m1, m2, ToString[WignerD[{j, m1, m2}, psi, theta, phi], InputForm]},
     {j, 0, 5}, {m1, -j, j}, {m2, -j, j} ], 2],
  TableHeadings -> {"j", "m1", "m2", "WignerD[{j, m1, m2}, psi,...
Can you write Python code for it?

Rotation.D(j, m, mp, alpha, beta, gamma)


I am working on the file "Notes/conventions.ipynb".
The first task is:
This is precisely the same matrix as Mathematica returns from EulerMatrix[{ψ, θ, ϕ}], which would suggest to me that my Euler conventions are the same as Mathematica's.
Compare Mathematica's expressions to SymPy's
Can you write Python code for it?

j, m1, m2 = sympy.symbols('j, m1, m2', integer=True)
#psi, theta, phi = sympy.symbols('psi, theta, phi', real=True)

with open('conventions_mathematica.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader, None)
    print('Mathematica header:', ', '.join(header))
    mathematica_wignerD = {
        tuple(int(s) for s in row[:3]): sympy.sympify(mathematica(row[3]))
        for row in reader
    }


I am working on the file "Notes/conventions.ipynb".
The first task is:
Unfortunately, I can't get sympify to correctly use locals, so I have to just grab all the symbols that it created in the previous cell, as follows:
Can you write Python code for it?

free_symbols = list(set(symbol for jm1m2 in mathematica_wignerD for symbol in mathematica_wignerD[jm1m2].free_symbols))

sorted(free_symbols, key=lambda s: str(s))

phi, psi, theta = sorted(free_symbols, key=lambda s: str(s))

j, m, mp = sympy.symbols('j, m, mprime', integer=True)
alpha, beta, gamma = sympy.symbols('alpha, beta, gamma', real=True)


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
150 instances and 4 features
Can you write Python code for it?


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
3 group to classify
Can you write Python code for it?


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
Check if there is any null values
Can you write Python code for it?


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
Check the encoded values
Can you write Python code for it?


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
Default Logistic Regression(optional)
Can you write Python code for it?

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn import metrics

modelLR = LogisticRegression(n_jobs=-1)

modelLR.fit(X_train,y_train);

y_pred = modelLR.predict(X_test)
modelLR.score(X_test,y_pred)

confusion_matrix=metrics.confusion_matrix(y_test,y_pred)
confusion_matrix

import matplotlib.pyplot as plt
%matplotlib inline

LABEL_COLOR_MAP = {0 : 'g',
                   1 : 'y',
                   2 : 'r'
                  }

pred_color = [LABEL_COLOR_MAP[i] for i in y_pred]
test_color = [LABEL_COLOR_MAP[i] for i in y_test]

fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(5,2))

axes[0].scatter(X_test[:,0],X_test[:,1], c= pred_color)
axes[0].set_title('Predicted')
axes[1].scatter(X_test[:,0],X_test[:,1], c= test_color)
axes[1].set_title('True');


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
PCA(optional)
Can you write Python code for it?

from sklearn.decomposition import PCA
pca = PCA()
pca.fit_transform(X)

covariance = pca.get_covariance()
explained_variance = pca.explained_variance_
explained_variance

import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(6, 4))

plt.bar(range(4), explained_variance, alpha=0.5, align='center',
            label='individual explained variance')
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.legend(loc='best')
plt.tight_layout()


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
The last 1 componen has less amount of variance of the data. The first 3 components retains more than 90% of the data.(Here, compared with only 4 features, there're enough instances to support the final results. We shall take all features into consideration)
Consider first 3 components and visualise it using K-means clustering
Can you write Python code for it?

from sklearn.cluster import KMeans
from sklearn.decomposition import PCA

pca = PCA(n_components=3)
x_pca = pca.fit_transform(X)

kmeans = KMeans(n_clusters=3, random_state=5)
x_clustered = kmeans.fit_predict(x_pca)

y = targets.values
y = y.reshape(y.size)

import matplotlib.pyplot as plt
%matplotlib inline

LABEL_COLOR_MAP = {0 : 'g',
                   1 : 'y',
                   2 : 'r'
                  }

label_color = [LABEL_COLOR_MAP[i] for i in x_clustered]
y_color = [LABEL_COLOR_MAP[i] for i in y]

fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(5,3))

axes[0].scatter(X[:,0],X[:,1], c= label_color)
axes[0].set_title('PCA')
axes[1].scatter(X[:,0],X[:,1], c= y_color)
axes[1].set_title('True Cluster');


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
Tuned Logistic Regression(optional)
Can you write Python code for it?

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn import metrics
from sklearn.model_selection import GridSearchCV

LRs= LogisticRegression()

tuned_parameters = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000] ,
              'penalty':['l1','l2']
                   }

modelLR=GridSearchCV(LRs, tuned_parameters,cv=10)


I am working on the file "Notes/preprocess/Iris Demo.ipynb".
The first task is:
Using K-means, we are able to segregate 3 classes well using the first 3 components with maximum variance. (Don't mind the color type, which is meaningless in clustering).
You can apply PCA firstly before using machine learning in the next steps
Splitting the data into training and testing dataset
Can you write Python code for it?

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=4)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
ATTENTION
La fonction sin du module math de Python ne peut pas être appelée sur des expressions symboliques, car elle assume que l'argument est un nombre réel (type float):
Can you write Python code for it?

from sympy.abc import
from math import sin
sin(x)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Affichage automatique des résultats en LaTeX
Pour que les résultats soient affichés en LaTeX automatiquement, il suffit d'utiliser la commande suivante une seule fois pour le fichier:
Can you write Python code for it?

from sympy import init_printing
init_printing(use_latex='mathjax')


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Alternativement, on peut aussi utiliser la fonction together. À la différence de ratsimp la fonction together préserve le plus possible les termes sous la forme initiale:
Can you write Python code for it?

from sympy import together
together(1/(x+1) + 1/y + 1/z)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Cela permet de faire des calculs exacts. Par exemple, le sinus d'un angle de $\pi/3$ est égal à la racine de trois sur deux:
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Cette variable peut être additionnée, soustraite, multipliée et divisée:
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Définir les variables symboliques x_1, x_2, ..., x_n
En SymPy, on peut créer plusieurs variables $x_i$ indicées pour $i=a,...,b-1$ à l'aide de la fonction symbols("xa:b") où a et b sont remplacés par des nombres entiers:
Can you write Python code for it?

from sympy import symbols
x4,x5,x6,x7,x8 = symbols("x4:9")
x4 + x5 + x6 + x7 + x8


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Expressions symboliques
On peut faire des calculs impliquant plus d'une variable:
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
L'expression symbolique est représentée par un arbre d'opérations.
<img src="images/expression.png" alt="image" width="302" />
Pour information, l'image a été créée avec Graphviz avec le resultat de la fonction dotprint :
Can you write Python code for it?

from sympy.printing.dot import dotprint
s = dotprint(expr)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
La fonction inverse du sinus aussi appelée arc sinus et représentée par la fonction asin dans SymPy peut retourner des expressions symboliques impliquant des constantes symboliques telles que le nombre $\pi$ :
Can you write Python code for it?

from sympy import asin, Rational
asin(1)

asin(Rational(1,2))


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
La fonction simplify performe une série de simplifications dans un ordre bien choisi. Les simplifications spécifiques incluent besselsimp, combsimp, exptrigsimp, hypersimp, nsimplify, powsimp, radsimp, ratsimp, ratsimpmodprime, signsimp, simplify, simplify_logic, trigsimp et d'autres encore. Il suffit de consulter le code simplify?? pour voir ce qui se passe et dans quel ordre.
Lorsque l'on sait exactement ce qu'on veut faire sur l'expression symbolique (factoriser, mettre sur un dominateur commun, etc.), on peut utiliser directement la bonne fonction. Cela peut retourner un résultat plus rapidement. Les plus importantes fonctions de modification d'expressions symboliques sont décrites dans les sections qui suivent. On trouvera plus d'informations sur les façons de simplifier une expression dans le tutoriel de SymPy: http://docs.sympy.org/latest/tutorial/simplification.html
Développer une expression
Pour développer une expression, on utilise la fonction expand :
Can you write Python code for it?

from sympy import expand
from sympy.abc import a,b
(a + b)**2

expand((a + b)**2)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
La racine de 3 ne peut pas être écrite exactement avec un nombre fini de décimales, car c'est un nombre irrationel. La façon la plus exacte d'exprimer la racine (positive) du nombre trois est de l'écrire tel quel. En SymPy, la racine carrée de 3 est exprimée symboliquement:
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Note: En IPython et Jupyter, la barre de soulignement (_) est une variable qui contient le dernier résultat calculé. Aussi, la double barre de soulignement (__) est une variable qui contient l'avant-dernier résultat calculé. Finalement, la triple barre de soulignement (___) est une variable qui contient l'avant-avant-dernier résultat calculé. La quadruple barre de soulignement ne contient rien.
Annuler les facteurs communs d'une fraction
Pour annuler les facteurs communs dans une fonction rationnelle, on utilise cancel :
Can you write Python code for it?

expr = (x**2 + x*y) / x
expr

from sympy import cancel
cancel(expr)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
On peut aussi substituer une variable symbolique par une expression symbolique:
Can you write Python code for it?

from sympy import log
from sympy.abc import x,y,z
expression.subs({a:x**2, b:log(y), c:z})


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
On peut la décomposer en somme de fractions rationnelles à l'aide de la fonction apart de SymPy:
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
On rassemble les termes selon les puissances de x :
Can you write Python code for it?

from sympy import collect
collect(expr, x)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour factoriser le polynôme sur les nombres de Gauss (nombres complexes à parties imaginaire et réelle entières), on ajoute l'option gaussian=True :
Can you write Python code for it?

factor(x**3 - x**2 + x - 1, gaussian=True)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour faire la factorisation sur une extension algébrique des nombres rationnels, il suffit de spéficifier un ou des nombres algébriques qui engendrent l'extension:
Can you write Python code for it?

factor(x**2 - 5)

factor(x**2 - 5, extension=sqrt(5))


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour faire plus d'une substitutions, on peut les indiquer dans un dictionaire ({}) comme ci-bas:
Can you write Python code for it?

expression.subs({a:9, b:4})

expression.subs({a:9, b:4, c:100})


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour la mettre au même dénominateur, on utilise ratsimp :
Can you write Python code for it?

from sympy import ratsimp
ratsimp(1/(x+1) + 1/y + 1/z)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour plus de commodité, on peut importer les variables les plus souvent utilisées du sous-module abc :
Can you write Python code for it?

from sympy.abc import a, epsilon
a + a * a + epsilon


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Pour simplifier une expression, on utilise la commande simplify :
Can you write Python code for it?


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Rationalisation du dénominateur d'une expression
Pour rationaliser le dénominateur d'un expression, on utilise la fonction radsimp de SymPy:
Can you write Python code for it?

A = 1 / (1+sqrt(5))
A

from sympy import radsimp
radsimp(A)


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Réduire au même dénominateur
Une somme de fonctions rationnelles reste sous forme de somme:
Can you write Python code for it?

from sympy.abc import x,y,z
1/(x+1) + 1/y + 1/z


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Simplifier une expression
Les expressions ne sont pas toujours simplifiées:
Can you write Python code for it?

from sympy import sin,cos
from sympy.abc import a
r = sin(a)**2 + cos(a)**2
r


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Variable symbolique
La fonction Symbol de SymPy permet de créer une variable symbolique:
Can you write Python code for it?

from sympy import Symbol
a = Symbol("a")     # le symbole a est stocké dans la variable a
a


I am working on the file "NotesDeCours/04-calcul-symbolique.ipynb".
The first task is:
Voici un autre exemple:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Attention: Pour résoudre un système d'équations, il faut absoluement mettre les équations dans une liste [eq1, eq2] entre crochets []. Autrement, on obtient une erreur:
Can you write Python code for it?

In [279]: solve(eq1, eq2)
Traceback (most recent call last):
...
TypeError: cannot determine truth value of
x - y == 33


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Cela fonctionne aussi pour des systèmes d'équations non linéaires. Par exemple pour trouver deux nombres dont la somme est 47 et dont le produit est 510:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Cela fonctionne aussi s'il y a plus d'une solution:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
La fonction roots trouve les formules qui expriment les racines d'un polynôme quadratique:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
La syntaxe abrégée peut aussi être utilisée pour résoudre un système d'équations. Dans l'exemple qui suit, on calcule les points d'intersection d'une ellipse et d'une droite:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Le résultat est un dictionnaire ({}) qui associe à chaque racine sa multiplicité. La fonction roots trouve aussi les racines complexes:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Les coefficients des polynômes peuvent être des variables symboliques:
Can you write Python code for it?

from sympy.abc import a,b,c
roots(a*x + b, x)


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Résoudre un système d'équations
La fonction solve permet aussi de résoudre un système d'équations. Par exemple pour trouver deux variables x et y telle que leur somme vaut 47 et leur différence vaut 33:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Résoudre une équation
La fonction solve permet de résoudre une équation:
Can you write Python code for it?

from sympy import solve
solve(Eq(x, 3), x)

solve(Eq(x + y, 3), x)


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Syntaxe abrégée
Souvent on désire résoudre des équations dont l'un des termes est zéro: solve(Eq(expression,0)). Pour ce cas, il est équivalent d'écrire solve(expression) et la fonction solve trouvera les valeurs des variables avec lesquelles expression est évaluée à zéro. Les exemples ci-haut s'écrivent de la façon suivante avec cette syntaxe abrégée:
Can you write Python code for it?


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Trouver les racines d'une fonction
La fonction roots permet de calculer les racines d'une fonction polynomiale univariée :
Can you write Python code for it?

from sympy import roots
roots(x - 7)

roots(x**6)


I am working on the file "NotesDeCours/05-resolution-equation.ipynb".
The first task is:
Un exemple sur un polynôme de degré 3:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/region.png" alt="image" width="302" />
Pour tracer la région définie par plusieurs inégalités, on utilise la fonction And de sympy:
Can you write Python code for it?

from sympy import And
plot_implicit(And(y>2*x+1, y<5*x, x+y<5))


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/region_bornee.png" alt="image" width="302" />
Dessiner une fonction complexe avec mpmath
mpmath est une librairie Python pour faire des calculs en précision arbitraire sur les nombres flottants. Elle permet aussi de faire des dessins de fonctions complexes.
La façon d'importer la librairie mpmath n'est pas exactement la même selon qu'on utilise une installation normale de SymPy ou qu'on utilise SageMath:
Can you write Python code for it?

from sympy import mpmath    # Sympy (installation normale)
import mpmath               # SageMath


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/sin10x_cos4y.png" alt="image" width="264" />
On trouvera d'autres exemples en consultant la documentation de plot? et plot3d? ou dans la section Plotting du tutoriel de Sympy: http://docs.sympy.org/latest/modules/plotting.html
Dessiner une fonction $\RR\to\RR^2$
Dans cette section et les suivantes, on aura utilisera les fonctions et variables symboliques suivantes:
Can you write Python code for it?

from sympy import sin, cos
from sympy.abc import u, v


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/sin_x.png" alt="image" width="264" />
Un deuxième exemple sur l'intervalle $[-100, 100]$ :
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/sinx_x.png" alt="image" width="264" />
On trace une parabole de couleur rouge dans l'intervale $[-5, 5]$ avec un titre:
Can you write Python code for it?

plot(x**2+x-6, (x,-5,5), line_color='red', title='Youpi')


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/tore.png" alt="image" width="302" />
Dessiner les solutions d'une équation implicite
Can you write Python code for it?

from sympy import plot_implicit, Eq
from sympy.abc import x, y


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/x2_y2.png" alt="image" width="264" />
Un deuxième exemple:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/x_x2_x3.png" alt="image" width="226" />
Pour dessiner les trois fonctions avec des couleurs différentes, il faut créer un dessin à la fois et ensuite les combiner. L'option show=False permet d'éviter d'afficher les dessins intermédiaires:
Can you write Python code for it?

p1 = plot(x,    (x, -1, 1), show=False, line_color='b')
p2 = plot(x**2, (x, -1, 1), show=False, line_color='r')
p3 = plot(x**3, (x, -1, 1), show=False, line_color='g')


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/x_x2_x3_colors.png" alt="image" width="226" />
Tracer une fonction $\RR^2\to\RR$
On importe la fonction plot3d du sous-module sympy.plotting :
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
<img src="images/z.png" alt="image" width="264" />
Les couleurs de l'arc en ciel doivent être interprétés comme l'argument d'un nombre complexe (rouge pour un nombre réel positif). Le module du nombre complexe est représenté par la transparence (0=noir opaque, $\infty$ = oo = blanc transparent).
De la même façon, on ne peut pas utiliser le I de sympy avec mpmath, il faut utiliser les nombres complexes de Python. Le dessin suivant illustre la multiplication par le nombre complexe $i$, c'est-à-dire une rotation de 90 degrés:
Can you write Python code for it?

I = complex(0,1)         # le nombre complexe I de Python
mpmath.cplot(lambda z: I*z, [-10, 10], [-10, 10])


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
La fonction plot_implicit permet de tracer les solutions d'une équation implicite:
Can you write Python code for it?

eq = Eq(x**2+y**2+x*y-2*x, 5)
eq

plot_implicit(eq)


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
La syntaxe des arguments n'est pas exactement la même que pour la fonction plot de SymPy. Il faut définir une fonction Python avec la commande def ou encore sur une ligne avec lambda. Par exemple, la fonction identité peut s'écrire lambda z:z en Python.
On trace la fonction identité pour comprendre la signification de l'image obtenue:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
Maintenant p1 contient les trois graphes:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
On affiche le graphe des trois fonctions:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
Rappelons que sans la ligne suivante, les dessins ne s'afficheront pas:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
Tracer une fonction $\RR\to\RR$
On importe la fonction plot qui permet de dessiner des fonctions:
Can you write Python code for it?


I am working on the file "NotesDeCours/06-tracer-une-fonction.ipynb".
The first task is:
Un premier exemple:
Can you write Python code for it?

from sympy.abc import x,y
plot3d(x**2+y**2)


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Calcul différentiel
Pour dériver une fonction par rapport à une variable x, on utilise la fonction diff de sympy avec la syntaxe diff(fonction, x) :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Calcul intégral
Le calcul d'une intégrale indéfinie se fait avec la fonction integrate avec la syntaxe integrate(f, x) :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Calculer l'intégrale de $x^2 \cos(x)$ par rapport à $x$ :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Calculer l'intégrale définie de $x^2 \cos(x)$ par rapport à $x$ sur l'intervalle de $0$ à $\pi/2$ :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Cela est utile pour écrire des équations:
Can you write Python code for it?

A = Sum(1/n**2, (n, 1, oo))
B = Product(n, (n,1,10))
C = Derivative(sin(x**2), x)
D = Integral(1/x**2, (x,1,oo))
from sympy import Eq
Eq(A, A.doit())

Eq(B, B.doit())

Eq(C, C.doit())

Eq(D, D.doit())


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Cela fonctionne aussi avec des variables différentes:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Cette section concerne le calcul différentiel et intégral. On trouvera d'autres exemples dans le tutoriel de Sympy sur le même sujet: http://docs.sympy.org/latest/tutorial/calculus.html
Limites
Pour calculer la limite d'une expression lorsqu'une variable tend vers une valeur, on utilise la fonction limit de sympy avec la syntaxe limit(expression, variable, valeur). :
Can you write Python code for it?

from sympy import limit, sin, S
from sympy.abc import x


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
De façon équivalente, on peut aussi utilise la syntaxe expression.series(x, x0, n) :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Déjà, cela permet d'écrire f et f(x) :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Développement en séries
On calcule la série de Taylor d'une expression qui dépend de x au point x0 d'ordre n avec la syntaxe series(expression, x, x0, n). Par exemple, la série de Maclaurin (une série de Maclaurin est une série de Taylor au point $x_0=0$) de $\cos(x)$ d'ordre 14 est:
Can you write Python code for it?

from sympy import series, cos
from sympy.abc import x
series(cos(x), x, 0, 14)


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
En sympy, tout comme dans SageMath, le symbole oo représente l'infini $\infty$. Les deux o collés resemblent au symbole de l'infini 8 à l'horizontal. Les opérations d'addition, de soustraction, de multiplication, etc. sont possibles avec l'infini oo tant qu'elle soient bien définies. On doit l'importer pour l'utiliser:
Can you write Python code for it?

from sympy import oo
oo

5 - oo

oo - oo           # nan signifie "Not A Number"


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
La limite de $f(x)=2x+1$ lorsque $x \to 5/2$ :
Can you write Python code for it?

limit(2*x+1, x, S(5)/2)   # la fonction S permet de créer un nombre rationel


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Le début et la fin de l'intervalle des valeurs de n peut être donné par des variables symboliques:
Can you write Python code for it?

from sympy.abc import a,b
summation(n, (n,1,b))

summation(n, (n,a,b))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Le développement de Taylor de $\log$ se fait en $x_0=1$ :
Can you write Python code for it?

from sympy import log
series(log(x), x, 0)

series(log(x), x, 1)


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Les doubles sommes fonctionnent aussi avec des intervalles infinis:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
On calcule la dérivée de $\sin(x)$ :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
On peut calculer la limite d'une expression lorsque x tend vers plus l'infini:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
On peut définir les dérivées de f à l'aide de la fonction Derivative de sympy:
Can you write Python code for it?

from sympy import Derivative
Derivative(f(x), x)             # ordre 1

Derivative(f(x), x, x)          # ordre 2


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Par défaut, le développement est efféctuée en 0 et est d'ordre 6:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Par exemple, pour évaluer la limite lorsque x tend vers 0 de l'expression $(\sin(x)-x)/x^3$, on écrit:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Pour calculer la i-ème dérivée d'une fonction, on ajoute autant de variables que nécessaire ou bien on spécifie le nombre de dérivées à faire:
Can you write Python code for it?

diff(sin(x), x, x, x)

diff(sin(x), x, 3)


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Pour calculer la limite à gauche en un point, on doit spécifier l'option dir="-" :
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Pour définir la dérivée, on peut aussi utiliser .diff(). L'exemple précédent s'écrit:
Can you write Python code for it?

dsolve(Eq(f(x).diff(x, x) + 9*f(x), 1), f(x))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Puis, on peut la résoudre avec la fonction dsolve de sympy avec la syntaxe dsolve(equation, f(x)) et trouver quelle fonction f(x) est égale à sa propre dérivée:
Can you write Python code for it?

from sympy import dsolve
dsolve(Eq(f(x), Derivative(f(x),x)), f(x))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Résoudre une équation différentielle ordinaire comme $f''(x) + 9 f(x) = 1$ :
Can you write Python code for it?

dsolve(Eq(Derivative(f(x),x,x) + 9*f(x), 1), f(x))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Si la série est divergente, elle sera évaluée à oo ou encore elle restera non évaluée:
Can you write Python code for it?

summation(n, (n,1,oo))

summation((-1)**n, (n,1,oo))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Sommes
En Python, il existe une fonction (sum) que l'on a pas besoin d'importer et qui permet de calculer la somme des valeurs d'une liste:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Sympy procède à des simplifications lorsque possible:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Voici quelques autres exemples:
Can you write Python code for it?

diff(cos(x**3), x)

diff(atan(2*x), x)

diff(1/tan(x), x)


from sympy import exp
integrate(cos(x)*exp(x), x)

integrate(x**2, (x,0,1))


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Voici un autre exemple:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
et aussi lorsque x tend vers moins l'infini:
Can you write Python code for it?


I am working on the file "NotesDeCours/07-limites-calcul-diff.ipynb".
The first task is:
Équations différentielles
Une équation différentielle est une relation entre une fonction inconnue et ses dérivées. Comme la fonction est inconnue, on doit la définir de façon abstraite comme ceci:
Can you write Python code for it?

from sympy import Function
f = Function("f")


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
Avant de pouvoir mettre à jour une variable, vous devez l'initialiser à une valeur de départ, habituellement avec une valeur simple:
Can you write Python code for it?

sous_total = 0
sous_total = sous_total + 1


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
Dans ce chapitre et les suivants, nous traitons de la programmation en Python. Les notes ici présentent les grandes lignes et les éléments principaux de ce sujet. Le lecteur désirant en savoir plus sera invité à consulter les chapitres 1 à 7 du livre en français de G. Swinnen Apprendre à programmer avec Python 3 [Swinnen]_, le syllabus du cours de programmation de Thierry Massart [Massart]_ ou encore les chapitre 1 à 11 du livre en anglais de Wentworth et al. How to Think Like a Computer Scientist - Learning with Python [Thinklike]_.
Une boucle permet de faire des tâches répétitives sur un ordinateur avec un moindre effort.
<img src="images/bart_simpson.jpg" alt="image" width="264" />
Can you write Python code for it?


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
L'exemple suivant double chacune des lettres d'une chaîne de caractères:
Can you write Python code for it?


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
La boucle for
La boucle for permet aussi de parcourir les éléments d'une liste, une chaîne de caractères ou en général de tout objet itérable:
Can you write Python code for it?

for a in [1,2,3,4]:

for a in 'bonjour':


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
La syntaxe a == 5 est réservée pour le test d'égalité.
Mise à jour d'une variable
Quand une instruction d'affectation est exécutée, l'expression de droite (à savoir l'expression qui vient après le signe = d'affectation) est évaluée en premier. Cela produit une valeur. Ensuite, l'assignation est faite, de sorte que la variable sur le côté gauche se réfère maintenant à la nouvelle valeur.
L'une des formes les plus courantes de l'affectation est une mise à jour, lorsque la nouvelle valeur de la variable dépend de son ancienne valeur:
Can you write Python code for it?


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
Le bloc d'instructions est exécuté autant de fois qu'il y a d'éléments dans la liste. Le bloc d'instruction est exécuté une fois pour chaque valeur de la variable i dans la liste.
Un exemple de boucle for avec Sympy
Supposons que l'on désire factoriser le polynôme $x^k-1$ pour toutes les valeurs de $k=1,...,9$. En SymPy, il est possible d'écrire onze fois le même calcul où on change la valeur de l'exposant $k$ à chaque fois:
Can you write Python code for it?

from sympy import factor
from sympy.abc import x
factor(x**1-1)

factor(x**2-1)

factor(x**3-1)

factor(x**4-1)

factor(x**5-1)

factor(x**6-1)

factor(x**7-1)

factor(x**8-1)

factor(x**9-1)


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
Lorsque la variable de la boucle n'est pas utilisée dans le bloc d'instruction la convention est d'utiliser la barre de soulignement (_) pour l'indiquer. Ici, on calcule les puissances du nombre 3. On remarque que l'expression d'assignation k *= 3 est équivalente à k = k * 3 :
Can you write Python code for it?


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
On vérifie que le calcul est bon:
Can you write Python code for it?


I am working on the file "NotesDeCours/13-boucle-for.ipynb".
The first task is:
Quelques exemples
L'exemple suivant illustre comment calculer la somme des éléments d'une liste en utilisant une variable s initialisée à zéro avant la boucle:
Can you write Python code for it?


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
Bien sûr, on pourrait aussi améliorer la prise de décision en considérant la distance de la prochaine station d'essense et comparer avec la distance pouvant être parcourue avec ce qui reste d'essence, etc. Mais, pour le moment, l'important est de comprendre comment on écrit une condition simple en Python.
La forme if - else
La forme générale est la suivante:
Can you write Python code for it?

if <condition>:
    <code exécuté si la condition est satisfaite, i.e., True>
else:
    <code exécuté si la condition n'est pas satisfaite, i.e., False>


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
Ci-haut, une seule des lignes print sera exécutée: celle qui est sous la première condition est qui satisfaite. Attention, ici comme les conditions ne sont pas mutuellement exclusives, l'ordre des conditions est important.
Syntaxe compacte d'une assignation conditionnelle
Parfois, on veut assigner à une variable une valeur qui dépend d'une condition. Par exemple, on veut calculer le minimum de deux valeurs. On peut utiliser une condition pour faire cette assignation:
Can you write Python code for it?


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
La <condition> est une expression qui retourne une valeur booléenne True ou False. Elle s'écrit avec un if et la ligne doit se terminer avec les deux points :. Si la condition est vérifiée, c'est-à-dire si la condition est évaluée à True, alors le code indenté de 4 espaces sous la ligne if est exécuté. Sinon, c'est-à-dire si la condition est évaluée à False, alors c'est le code indenté de 4 espaces sous la ligne else: qui est exécuté.
La forme if - elif - else
Parfois, il y a plusieurs cas à tester. Il est possible d'emboîter les conditions:
Can you write Python code for it?

if reservoir == 0:
    print("Panne d'essence")
else:
    if 0 < reservoir < 0.15:
        print('Prendre la sortie')
    else:
        print('Rester sur l'autoroute')


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
La forme if seul
La ligne elif ou la ligne else n'est pas obligatoire car parfois on ne veut rien faire si la condition n'est pas satisfaite. Dans ce cas, on écrit simplement:
Can you write Python code for it?

if reservoir == 0:
    print("Panne d'essence")


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
Les conditions sont, avec les boucles, les éléments les plus importants de la programmation. Elles permettent de formaliser la prise de décisions selon l'information disposée. Faisons un exemple, supposons que nous sommes sur l'autoroute en voiture et que l'on peut faire le plein à la prochaine sortie. Est-ce qu'on prend la sortie ou est-ce qu'on reste sur l'autoroute? Supposons que la variable reservoir prend une valeur entre 0 et 1 et indique le pourcentage d'espace occupé par l'essence dans le réservoir. Une première façon de prendre la décision pourrait s'écrire en Python:
Can you write Python code for it?

if reservoir < 0.15:
    print('Prendre la sortie')
else:
    print('Rester sur l'autoroute')


I am working on the file "NotesDeCours/14-conditions.ipynb".
The first task is:
Python offre une syntaxe abrégée (inspirée du C) pour faire ceci:
Can you write Python code for it?


I am working on the file "NotesDeCours/15-fonctions.ipynb".
The first task is:
Cette fonction permet de tester le code sur la température de l'eau plus facilement:
Can you write Python code for it?

etat_de_leau(23)

etat_de_leau(-23)

etat_de_leau(0)

etat_de_leau(0.1)

etat_de_leau(102)


I am working on the file "NotesDeCours/15-fonctions.ipynb".
The first task is:
La ligne d'en-tête commence avec def et se termine par un deux-points. Le choix du nom de la fonction suit exactement les mêmes règles que pour le choix du nom d'une variable. Un bloc constitué d'une ou plusieurs instructions Python, chacune indentée du même nombre d'espace (la convention est d'utiliser 4 espaces) par rapport à la ligne d'en-tête. Nous avons déjà vu la boucle for qui suit ce modèle.
Le nom de la fonction est suivi par certains paramètres entre parenthèses. La liste des paramètres peut être vide, ou il peut contenir un certain nombre de paramètres séparés les uns des autres par des virgules. Dans les deux cas, les parenthèses sont nécessaires. Les paramètres spécifient les informations, le cas échéant, que nous devons fournir pour pouvoir utiliser la nouvelle fonction.
La ou les valeurs de retour d'une fonction sont retournées avec la commande return. Par exemple, la fonction qui retourne la somme de deux valeurs s'écrit:
Can you write Python code for it?

def somme(a, b):
    return a + b

somme(4,7)


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
En utilisant cette fonciton, on trouve que la liste des premiers nombres premiers inférieurs à 20 est:
Can you write Python code for it?

[n for n in range(20) if est_premier(n)]


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
Mais il y a encore une erreur, car 0 et 1 ne devraient pas faire partie de la liste. Une solution est de traiter ces deux cas de base à part:
Can you write Python code for it?

from math import sqrt
def est_premier(n):
    if n == 0 or n == 1:
        return False
    sq = int(sqrt(n))
    for i in range(2, sq+1):
        if n % i == 0:
            return False
    return True


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
On a vu dans les chapitres précédents comment définir des fonctions avec def, des boucles avec while et for et des tests avec if ainsi que quelques exemples sur chaque notion mais indépendants des autres. Très souvent en programmation, on a besoin d'utiliser plus tous ces outils à la fois. C'est leur utilisation simultanée qui permet de résoudre des problèmes très divers et de les exprimer en quelques lignes de code.
Dans ce chapitre, nous allons voir quelques exemples qui utilisent les fonctions, les boucles et les conditions dans un même programme.
Conjecture de Syracuse
La suite de Syracuse une suite d'entiers naturels définie de la manière suivante. On part d'un nombre entier plus grand que zéro ; s’il est pair, on le divise par 2 ; s’il est impair, on le multiplie par 3 et on ajoute 1. En répétant l’opération, on obtient une suite d'entiers positifs dont chacun ne dépend que de son prédécesseur. Par exemple, la suite de Syracuse du nombre 23 est:

23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, ...

Après que le nombre 1 a été atteint, la suite des valeurs (1, 4, 2, 1, 4, 2, ...) se répète indéfiniment en un cycle de longueur 3, appelé cycle trivial.
La conjecture de Syracuse est l'hypothèse selon laquelle la suite de Syracuse de n'importe quel entier strictement positif atteint 1. En dépit de la simplicité de son énoncé, cette conjecture défie depuis de nombreuses années les mathématiciens. Paul Erdos a dit à propos de la conjecture de Syracuse : "les mathématiques ne sont pas encore prêtes pour de tels problèmes".
Can you write Python code for it?

def syracuse(n):
    while n != 1:
        print(n, end=' ')
        if n % 2 == 0:
            n = n//2
        else:
            n = 3*n+1

syracuse(23)

syracuse(245)

syracuse(245154)


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
On pourrait faire plus efficace, car il suffit de vérifier la non-existence de diviseurs inférieurs à la racine carrée de n.
Can you write Python code for it?

from math import sqrt
def est_premier(n):
    sq = int(sqrt(n))
    for i in range(2, sq):
        if n % i == 0:
            return False
    return True


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
On vérifie que la fonction marche bien:
Can you write Python code for it?

diviseurs(12)

diviseurs(13)

diviseurs(15)

diviseurs(24)


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
On vérifie que la fonction retourne bien que 4 et 8 ne sont pas des nombres premiers:
Can you write Python code for it?


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
On vérifie que tout marche bien maintenant:
Can you write Python code for it?

[n for n in range(50) if est_premier(n)]


I am working on the file "NotesDeCours/17-exemples.ipynb".
The first task is:
Pouvez-vous trouver un nombre n tel que la suite de Syracuse n'atteint pas le cycle 4-2-1?
Énumérer les diviseurs d'un nombre entier
Une fonction qui retourne la liste des diviseurs d'un nombre entiers peut s'écrire comme ceci en utilisant une boucle for et un test if :
Can you write Python code for it?

def diviseurs(n):
    L = []
    for i in range(1, n+1):
        if n % i == 0:
            L.append(i)
    return L


I am working on the file "Notifications research.ipynb".
The first task is:
25 or more
Can you write Python code for it?

beyond_threshold(unreads, wikis, 24, "over")


I am working on the file "Notifications research.ipynb".
The first task is:
5 or more?
Can you write Python code for it?

beyond_threshold(notifs, wikis, 4, "over")


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

fig, axarr = plt.subplots( 5, 1, figsize=(12,30) )
fig.suptitle("Unread notifications per user", fontsize=24)
fig.subplots_adjust(top=0.95)
i = 0
for wiki in wikis:
    plot_by_wiki(unreads, wiki, ax = axarr[i])
    i = i + 1


I am working on the file "Notifications research.ipynb".
The first task is:
So, as expected, all the wikis have a pretty regular power-law distribution of notifications.
Unread notifications
First, the counts and percentages for various levels of unread notifications.
Under 5
Can you write Python code for it?

beyond_threshold(unreads, wikis, 5, "under")


I am working on the file "Notifications research.ipynb".
The first task is:
That's lower than I expected at English Wikipedia. It only had about 1,200 users with at least 30 notifications per month, compared to 3,500 highly active users (100+ edits) per month. However, both Flow wikis have higher percentages than the non-Flow wikis.
Now, let's look at the actual distributions. To make it easier to comprehend, I'll cut off the 90%+ of users with fewer than 5 notifications. I'll also cut off the users with 100 or more. How many is that?
Can you write Python code for it?

beyond_threshold(notifs, wikis, 99, "over")


I am working on the file "November 03, 2016/Covered in class.ipynb".
The first task is:
Function Defaults
By default a function without a return statement will give the result None.
Can you write Python code for it?

def add_all(*numbers):
    number = 0

    for num in numbers:
        number += num

    return number

print(add_all(1, 2, 3, 4, 5, 6, 7, 8, 9))

def multiply_and_sum(x, *args):
    """
    Returns the results of multiplying x by all
    passed arguments and then adding the results
    of each multiplication together
    """
    all_by_x = [arg * x for arg in args]
    return sum(all_by_x)

def multiply_and_sum_no_return(x, *args):
    """
    Same as mutiply_and_sum only returns nothing
    and is therefore useless
    """
    multiply_and_sum(x, *args)

values = [1,2,3,4]
result = multiply_and_sum_no_return(3, *values)

print("The result of no return is:", result)

result = multiply_and_sum(3, *values)
print("\nThe result of a return is: ", result)


I am working on the file "November 03, 2016/Covered in class.ipynb".
The first task is:
Functions calling themselves
This is known as recursion
Can you write Python code for it?

import math

def factorial(n):
    for number in range(n, 1, -1):
        return number * factorial(number - 1)

    return 1

print(factorial(3))
print(3 * 2 * 1)
print(math.factorial(3))

print(factorial(9))
print(9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1)
print(math.factorial(9))


I am working on the file "November 03, 2016/Covered in class.ipynb".
The first task is:
Thanks for another wagon wheel
Garret
Can you write Python code for it?

import turtle

def drawSquare():
   for i in range(4):
       alex.forward(100)
       alex.left(90)

def drawWindow():
   for i in range(4):
       drawSquare()
       alex.left(90)

wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.speed(9)
alex.color("blue")

for i in range(5):
   drawWindow()
   alex.left(18)


I am working on the file "November 03, 2016/Covered in class.ipynb".
The first task is:
Writing Code
Be sure when writing code to follow PEP-0008 https://www.python.org/dev/peps/pep-0008/
This is the defacto Python style guide for writing code. You can think of it how English writers might think of MLA or ALA.
Studio: Wagon Wheel
Thanks James!
WEbsite for running: https://trinket.io/python
Can you write Python code for it?

import turtle
import random

def draw_square(turt,sideLength):
   """Returns nothing draws a square """
   turt.color(random.choice(["red","orange","yellow","blue","purple"]))
   turt.begin_fill()
   for _ in range(4):
       turt.forward(sideLength)
       turt.left(90)
   turt.end_fill()

def draw_four_square(turt,sideLength):
   """Return None draws a group of four squares that form a larger square"""
   for index in range(4):
       if(index == 0):
           draw_square(turt,sideLength)
       elif(index == 1):
           turt.penup()
           turt.backward(sideLength)
           turt.pendown()
           draw_square(turt,sideLength)
       elif(index == 2):
           turt.penup()
           turt.right(90)
           turt.forward(sideLength)
           turt.left(90)
           turt.pendown()
           draw_square(turt,sideLength)
       elif(index == 3):
           turt.forward(sideLength)
           draw_square(turt,sideLength)
   reset_turtle_to_origin(turt)

def draw_square_rotate(turt,sideLength,num):
   """Returns None draws four square and regular intervals over 360 based on num """
   for angle in range(0,360,360//num):
       turt.left(angle)
       draw_four_square(turt,sideLength)

def reset_turtle_to_origin(turt):
   turt.penup()
   turt.setheading(0)
   turt.goto(0,0)
   turt.pendown()

def main():
   # Create window
   wn = turtle.Screen()

   # Create turtle
   turt = turtle.Turtle()
   turt.speed(0)

   # draw square
   draw_square_rotate(turt,100,5)

main()

print(8//3)

print(-7//3)

print(-7/3)

import math

print(round(-7/3))


I am working on the file "November 07, 2016/Covered in class.ipynb".
The first task is:
Thinking about how results work
Look at truth tables to understand how values can be combined for these binary operators: https://en.wikipedia.org/wiki/Truth_table#Logical_conjunction_.28AND.29
Also understand the not unary operator:
https://en.wikipedia.org/wiki/Truth_table#Logical_negation
Can you write Python code for it?

def factorial(number):
    """
    Return the factorial of a passed number.
    e.g. if 5 is passed return: 5 * 4 * 3 * 2 * 1
    """
    if number == 0:
        return 1

    return number * factorial(number -1)

import math

print(factorial(5))
print(math.factorial(5))


I am working on the file "November 14, 2016/Covered in class.ipynb".
The first task is:
Immutable
Can you write Python code for it?

set_of_values = [1,2,3,4]
print(set_of_values)
set_of_values[0] = 'meow cats'
print(set_of_values)

string_cannot_change = 'I am not changable'
print(string_cannot_change)

string_cannot_change = 10
print(string_cannot_change)

string_cannot_change = 'é'
print(string_cannot_change)

string_cannot_change = 'A different string is okay, but why?'
print(string_cannot_change)

string_cannot_change[7] = 'T'
string_cannot_change[7] = 'This will error'


I am working on the file "November 14, 2016/Covered in class.ipynb".
The first task is:
String Comparison
Don't compare strings without normalizing them first.
For example don't compare "How"  to "MeoW"  compare "how" to "meow"
Can you write Python code for it?

import random

def determine_character(character):
    if 1 == random.randint(0,1):
        return character
    return ''

name = 'GaRrY PolLEy'
new_name = ''
for character in name:
    new_name = new_name + determine_character(character)
    print(character, ':', ord(character))

print(ord('A'))
print(ord('a'))
print(new_name)

first_word = input("What is the first word: ")
second_word = input("What is the second word: ")

# Exmaple text that needs normalized
what_street = 'Maple Street'
another_street = 'maple street'

normalized_first_word = first_word.lower()
normalized_second_word = second_word.lower()

print(normalized_first_word, ':', normalized_second_word)

# Boolean assignment
are_words_the_same = normalized_first_word == normalized_second_word
print("The strings are the same once normalized?", are_words_the_same)


I am working on the file "November 14, 2016/Covered in class.ipynb".
The first task is:
Studios: Sorted
https://runestone.launchcode.org/runestone/static/thinkcspy/Studios/sorted.html
Can you write Python code for it?

# Cheating answer
def is_sorted(string):
    """Returns True if string is sorted from least to greatest
       False otherwise.
    """
    return ''.join(sorted(string)) == string

print('value', is_sorted('value'))
print('abc', is_sorted('abc'))
print('aBc', is_sorted('aBc'))

def is_sorted(string):
    for i in range(1, len(string)):

        previous_location = i - 1
        if string[previous_location] > string[i]:
            return False

    return True

print(is_sorted('ABC'))
print(is_sorted('BBC'))
print(is_sorted('CBC'))
print(is_sorted('CBS'))
print(is_sorted('NBC'))
print(is_sorted('aBc'))
print('a', ord('a'), 'B', ord('B'))

def is_sorted(string):
    n = 1

    for char in string:

        if char <= string[n]:
            n = n + 1

            if n == len(string):
                return True
        else:
            return False

    return False

print(is_sorted('ABC'))
print(is_sorted('BBC'))
print(is_sorted('CBC'))
print(is_sorted('CBS'))
print(is_sorted('NBC'))
print(is_sorted('aBc'))

def is_valid_password(string):
   upper_check = False
   lower_check = False
   char_check = False
   char_list = "!@#$%^&*()-_+"

   for char in string:

       if (ord(char) >= 65) and (ord(char) <= 90):
           upper_check = True

       if (ord(char) >= 97) and (ord(char) <= 122):
           lower_check = True

       if char in char_list:
           char_check = True

   return upper_check and lower_check and char_check and len(string) > 12

print(chr(65), chr(90), chr(97), chr(122))
is_valid_password('$aAjfasdfasdfasdfasdf')


I am working on the file "November 21, 2016/Covered in class.ipynb".
The first task is:
Adding to lists
Can you write Python code for it?

def starts_with_a(word):
    if type(word) is str:
        return word.startswith('a')

foods_bar = ['apple', 'anise', 'blueberry', 'pizza', 'chips']
foods_foo = ['chicken', 'apricote', 'charmander']
foods_starting_with_a = []

for food in foods_bar:
    if starts_with_a(food):
        foods_starting_with_a.append(food)

for food in foods_foo:
    if starts_with_a(food):
        foods_starting_with_a.append(food)

print(foods_starting_with_a)

numbers = [1,2,3,4]
numbers_two = [5,6,7,8]

print(numbers)
print(numbers_two)

starting_numbers = [list(numbers), numbers_two]
print(starting_numbers)

print(id(starting_numbers))
print(id(numbers))
print(id(starting_numbers[0]))

numbers.append(200)

print(numbers)
print(starting_numbers)


I am working on the file "November 21, 2016/Covered in class.ipynb".
The first task is:
Assignment and how it works
Using adding to lists to show you can modify one another.
Can you write Python code for it?

from pprint import pprint

fruit = ['apple', 'pear', 'grape']
non_perishable = ['chips', 'soup', 'cans']
meat = ['bologna', 'beef', 'turkey']

warehouse_foods = [
    fruit,
    non_perishable
]

material = ['cotton', 'hide', 'denim']
made_goods = ['gloves', 'boots', 'jeans']

warehouse_goods = [
    material,
    made_goods
]

warehouse_foods_and_goods = warehouse_foods + warehouse_goods

# Print out the lists of all foods and goods
print('Warehouse of foods and goods')
pprint(warehouse_foods_and_goods)
print()

# Change the food wharehouse to have another set of food
warehouse_foods.append(meat)
print('Warehouse of foods')
pprint(warehouse_foods)
print()

# See what's in the food and goods wharehouse again
print('Warehouse of foods and goods')
pprint(warehouse_foods_and_goods)
print()

# Add more fruit
fruit.append('peach')
print('Fruits')
print(fruit)
print()

# See what's in the food warehouse
print('Food warehouse')
pprint(warehouse_foods)
print()

# See what's in the food and goods ware house
print('Food and goods')
pprint(warehouse_foods_and_goods)
print()

# Remove the materials from the warehouse_goods
del warehouse_goods[1]
print('Warehouse of goods')
pprint(warehouse_goods)
print()

# See what's left in the food and goods warehouse
print('Warehouse of Foods and Goods')
pprint(warehouse_foods_and_goods)
print()

my_list = [2, 5, 3, 1]
# run first iteration bubble
my_list = [2, 3, 5, 1]
# run second iteraiton bubble
my_list = [2, 3, 1, 5]
# run third iteration bubble
my_list = [2, 1, 3, 5]
# run fourth iteration bubble
my_list = [1, 2, 3, 5]
# run fifth iteration bubble
# DONE my_list is sorted

# Bubble Sort implementation:

def bubble_sort (items):
    is_sorted = False
    while is_sorted is False:
        nswaps = 0
        for index in range(1, len(items)):
            previous_index = index - 1

            print(items)
            if items[previous_index] > items[index]:
                current_item = items[index]
                previous_item = items[previous_index]
             ...


I am working on the file "November 28, 2016/Covered in class 11-28-2016.ipynb".
The first task is:

Warning: list slicing will create a shallow copy ("clone") of nested lists.

Can you write Python code for it?

"""List slicing DOES NOT deeply copy nested objects."""
import time
delay = 2

hundreds = [100, 200, 300]
numbers = [1, hundreds]   # hundreds is nested
shallow_clone = numbers[:]
print("hundreds:", hundreds)
print("numbers:", numbers)
print("shallow_clone:", shallow_clone, "\n")
time.sleep(delay)

# verify that shallow_clone[0] == numbers[0]
print("shallow_clone[0] == numbers[0]:", shallow_clone[0] == numbers[0], "\n")
time.sleep(delay)

# modify the first element in numbers from 1 -> 10
numbers[0] = 10
print("numbers[0] = 10\n")
time.sleep(delay)

# test whether shallow_clone[0] also was modified
print("Was shallow_clone[0] also modified?",
      shallow_clone[0] == numbers[0], "\n")
time.sleep(delay)

# change the first element in the list of hundreds from 100 -> 500
numbers[1][0] = 500
print("numbers[1][0] = 500\n")
time.sleep(delay)

# test whether the list of hundreds in shallow_clone also has been modified
print("Was shallow_clone[1][0] also modified?",
      numbers[1][0] == shallow_clone[1][0], "\n")
time.sleep(delay)

# look at all of the variables
print("hundreds:", hundreds)
print("numbers:", numbers)
print("shallow_clone:", shallow_clone)


I am working on the file "November 28, 2016/Covered in class 11-28-2016.ipynb".
The first task is:
In the above example the general pattern:
[expression for variable in sequence if condition]
Becomes:
[i for i in range(1, 100) if i <= 3]
You can omit the condition when you want to take all of the values from the sequence.
A list comprehension without the optional if clause takes the form:
[expression for variable in sequence]
Can you write Python code for it?

"""Create a list from a list comprehension without an if clause."""
lst = [i for i in range(1, 11)]
print(lst)