%matplotlib inline
We create a list by putting values inside square brackets:
names = ['Alice', 'Bob', 'Carl']
type(names)
names.append('Dave')
names
names[:2]
names[0]
print(names)
print("Printing a name: " + names[0])
print("Printing a name: " + names[1])
print("Printing a name: " + names[2])
print("Printing a name: " + names[3])
for n in names:
print("Printing a name: " + n)
A for loop to repeat an operation---in this case, printing---once for each thing in a collection. The general form of a loop is:
for variable in collection: do things with variable
names.reverse()
print(names)
len(names)
len(names[0])
Write a cell in the notebook that computes the sum of the number of characters of each string in the names list
tot = 0
for name in names:
tot = tot + len(name)
print(tot)
def compute_total_characters(names):
tot = 0
for name in names:
tot = tot + len(name)
return tot
assert compute_total_characters([]) == 0
assert compute_total_characters(["a"]) == 1
assert compute_total_characters(["aa", "abc"]) == 5
Open the notebook http://nbviewer.ipython.org/github/zonca/challenges/blob/master/challenge-notebook-3.ipynb, the solution to this challenge is below
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
def fahr_to_celsius(temp_fahr):
"""Convert temperature from Fahrenheit to Celsius"""
temp_celsius = (temp_fahr - 32) * 5 / 9.0
return temp_celsius
def analyze(data):
"""Perform regression analysis on mosquito data
Performs a linear regression based on rainfall.
Creates a plot of the result and returns fit parameters.
Parameters
----------
data : pandas.Dataframe
Column named 'temperature', 'rainfall' and 'mosquitos'.
Returns
-------
parameters_rainfall : pandas.Series
Fit parameters named Intercept and rainfall
parameters_temperature : pandas.Series
Fit parameters named Intercept and temperature
"""
data['temperature'] = fahr_to_celsius(data['temperature'])
output = []
for variable in ['rainfall', 'temperature']:
# linear fit
regr_results = sm.OLS.from_formula('mosquitos ~ ' + variable, data).fit()
parameters = regr_results.params
line_fit = parameters['Intercept'] + parameters[variable] * data[variable]
# plotting
plt.figure()
plt.plot(data[variable], data['mosquitos'], '.', label="data")
plt.plot(data[variable], line_fit, 'red', label="fit")
plt.xlabel(variable)
plt.ylabel('mosquitos')
plt.legend(loc='best')
output.append(parameters)
return output
data_A2 = pd.read_csv('A2_mosquito_data.csv')
parameters_A2 = analyze(data_A2)
print(parameters_A2)
for variable in collection
to process the elements of a collection one at a time.len(thing)
to determine the length of something that contains other values.[value1, value2, value3, ...]
creates a list.