# Supplementary Practice Problems

These are similar to programming problems you may encounter in the mid-terms. They are not graded but we will review them in lab sessions.

**1**. (10 points) The logistic map is defined by the following simple function

$$
f(x) = rx(1-x)
$$

For $x_0 = 0.1$ and $r = 4.0$, store the first 10 values of the iterated logistic map $x_{i+1} = rx_i(1-x_i)$ in a list. The first value in the list should be $x_0$.


```python
def logistic(x, r):
    """Blah"""
    return r*x*(1-x)
```


```python
import numpy as np
```


```python
n = 10
xs = np.zeros(n)
xs[0] = 0.1
r = 4.0

for i in range(1, n):
    xs[i] = logistic(xs[i-1], r)
xs
```




    array([ 0.1       ,  0.36      ,  0.9216    ,  0.28901376,  0.82193923,
            0.58542054,  0.97081333,  0.11333925,  0.40197385,  0.9615635 ])



**2**. (10 points) Write a function to find the greatest common divisor (GCD) of 2 numbers using Euclid's algorithm.:

\begin{align}
\gcd(a,0) &= a \\
\gcd(a, b) &= \gcd(b, a \mod b)
\end{align}

Find the GCD of 5797 and 190978. 

Now write a function to find the GCD given a collection of numbers.

Find the GCD of (24, 48, 60, 120, 8).


```python
def gcd(a, b):
    """Blah"""
    if b == 0:
        return a
    else:
        return gcd(b, a % b)
```


```python
gcd( 5797, 190978)
```




    17




```python
from functools import reduce
```


```python
def gcds(xs):
    """Blah"""
    return reduce(lambda a, b: gcd(a, b), xs)
```


```python
xs = (24, 48, 60, 120, 8)
gcds(xs)
```




    4



**3**. (10 points) Find the least squares linear solution to the following data

```
y = [1,2,3,4]
x1 = [1,2,3,4]
x2 = [2,3,4,5]
```

That is, find the "best" intercept and slope for the variables `x1` and `x2`.


```python
from scipy.linalg import lstsq
```


```python
y = [1,2,3,4]
x1 = [1,2,3,4]
x2 = [2,3,4,5]

X = np.c_[np.ones(len(y)), x1, x2]
lstsq(X, y)
```




    (array([-0.33333333,  0.66666667,  0.33333333]),
     array([], dtype=float64),
     2,
     array([  9.34413269e+00,   8.28965828e-01,   1.18039779e-16]))



**4**. (10 points) Read the `mtcars` data frame from R to a `pandas` DataFrame. Find the mean `wt` and `mpg` for all cars grouped by the number of `gear`s.


```python
%load_ext rpy2.ipython
```


```python
mtcars = %R mtcars
```


```python
mtcars.groupby('gear')[['wt', 'mpg']].mean()
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>wt</th>
      <th>mpg</th>
    </tr>
    <tr>
      <th>gear</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>3.0</th>
      <td>3.892600</td>
      <td>16.106667</td>
    </tr>
    <tr>
      <th>4.0</th>
      <td>2.616667</td>
      <td>24.533333</td>
    </tr>
    <tr>
      <th>5.0</th>
      <td>2.632600</td>
      <td>21.380000</td>
    </tr>
  </tbody>
</table>
</div>



**5**. (10 points) Read the `iris` data frame from R to a `pandas` DataFrame. Make a `seaborn` plot showing a linear regression of `Petal.Length` (y) against `Sepal.Length` (x). Make a separate regression line for each `Species`.


```python
iris = %R iris
```


```python
%matplotlib inline
```


```python
import seaborn as sns
```


```python
sns.lmplot(x='Petal.Length', y='Sepal.Length', hue='Species', data=iris)
pass
```

**6**. (10 points) Write a function that can flatten a nested list of arbitrary depth. Check that

```python
flatten([1,[2,3],[4,[5,[6,7],8],9],10,[11,12]])
```

returns

```python
[1,2,3,4,5,6,7,8,9,10,11,12]
```

For simplicity, assume that the only data structure you will encounter is a list. You can check if an item is a list by using 

```python
isinstance(item, list)
```


```python
def flatten(xs, acc=[]):
    """Blah"""
    if not isinstance(xs, list):
        acc.append(xs)
    else:
        for x in xs:
            flatten(x)
    return acc
```


```python
flatten([1,[2,3],[4,[5,[6,7],8],9],10,[11,12]])
```




    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]



**7**. (10 points) Create the following table

```python
array([[  1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  1,   2,   1,   0,   0,   0,   0,   0,   0,   0,   0],
       [  1,   3,   3,   1,   0,   0,   0,   0,   0,   0,   0],
       [  1,   4,   6,   4,   1,   0,   0,   0,   0,   0,   0],
       [  1,   5,  10,  10,   5,   1,   0,   0,   0,   0,   0],
       [  1,   6,  15,  20,  15,   6,   1,   0,   0,   0,   0],
       [  1,   7,  21,  35,  35,  21,   7,   1,   0,   0,   0],
       [  1,   8,  28,  56,  70,  56,  28,   8,   1,   0,   0],
       [  1,   9,  36,  84, 126, 126,  84,  36,   9,   1,   0],
       [  1,  10,  45, 120, 210, 252, 210, 120,  45,  10,   1]])
```

Start with the first row

```
[  1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]
```

and build the subsequent rows using a simple rule that only depends on the previous row.


```python
xs = []

r = [ 0, 1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]
for i in range(10):
    s = [0]
    for x, y in zip(r[:], r[1:]):
        s.append(x + y)
    xs.append(s[1:])
    r = s
```


```python
np.array(xs)
```




    array([[  1,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0],
           [  1,   2,   1,   0,   0,   0,   0,   0,   0,   0,   0],
           [  1,   3,   3,   1,   0,   0,   0,   0,   0,   0,   0],
           [  1,   4,   6,   4,   1,   0,   0,   0,   0,   0,   0],
           [  1,   5,  10,  10,   5,   1,   0,   0,   0,   0,   0],
           [  1,   6,  15,  20,  15,   6,   1,   0,   0,   0,   0],
           [  1,   7,  21,  35,  35,  21,   7,   1,   0,   0,   0],
           [  1,   8,  28,  56,  70,  56,  28,   8,   1,   0,   0],
           [  1,   9,  36,  84, 126, 126,  84,  36,   9,   1,   0],
           [  1,  10,  45, 120, 210, 252, 210, 120,  45,  10,   1]])



**8**. (10 points) Read the following data sets into DataFrames. 

- url1 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills.csv"
- url2 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills2000.csv"

Create a new DataFraem only containing the names present in both DataFrames. Drop the `timef` column and have a single column for `dist` , `climb` and `time` that shows the average value of the two DataFrames. The final DtataFrame will thus have 4 columns (name, dist, climb, time).


```python
import pandas as pd
```


```python
url1 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills.csv"
url2 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills2000.csv"
```


```python
df1 = pd.read_csv(url1)
df2 = pd.read_csv(url2)
```


```python
df1.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Unnamed: 0</th>
      <th>dist</th>
      <th>climb</th>
      <th>time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Greenmantle</td>
      <td>2.5</td>
      <td>650</td>
      <td>16.083</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Carnethy</td>
      <td>6.0</td>
      <td>2500</td>
      <td>48.350</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Craig Dunain</td>
      <td>6.0</td>
      <td>900</td>
      <td>33.650</td>
    </tr>
  </tbody>
</table>
</div>




```python
df2.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Unnamed: 0</th>
      <th>dist</th>
      <th>climb</th>
      <th>time</th>
      <th>timef</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Tiso Carnethy</td>
      <td>6.0</td>
      <td>2500</td>
      <td>0.782222</td>
      <td>0.919167</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Criffel</td>
      <td>7.0</td>
      <td>1800</td>
      <td>0.793333</td>
      <td>1.003333</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Chapelgill</td>
      <td>1.5</td>
      <td>1400</td>
      <td>0.314444</td>
      <td>0.376667</td>
    </tr>
  </tbody>
</table>
</div>




```python
df = pd.merge(df1, df2, on='Unnamed: 0')
```


```python
df.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Unnamed: 0</th>
      <th>dist_x</th>
      <th>climb_x</th>
      <th>time_x</th>
      <th>dist_y</th>
      <th>climb_y</th>
      <th>time_y</th>
      <th>timef</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Craig Dunain</td>
      <td>6.0</td>
      <td>900</td>
      <td>33.650</td>
      <td>6.0</td>
      <td>900</td>
      <td>0.546111</td>
      <td>0.625833</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Ben Lomond</td>
      <td>8.0</td>
      <td>3070</td>
      <td>62.267</td>
      <td>9.0</td>
      <td>3192</td>
      <td>1.037778</td>
      <td>1.199167</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Goatfell</td>
      <td>8.0</td>
      <td>2866</td>
      <td>73.217</td>
      <td>8.0</td>
      <td>2866</td>
      <td>1.227778</td>
      <td>1.526389</td>
    </tr>
  </tbody>
</table>
</div>




```python
df = df.drop('timef', axis=1)
df.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Unnamed: 0</th>
      <th>dist_x</th>
      <th>climb_x</th>
      <th>time_x</th>
      <th>dist_y</th>
      <th>climb_y</th>
      <th>time_y</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Craig Dunain</td>
      <td>6.0</td>
      <td>900</td>
      <td>33.650</td>
      <td>6.0</td>
      <td>900</td>
      <td>0.546111</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Ben Lomond</td>
      <td>8.0</td>
      <td>3070</td>
      <td>62.267</td>
      <td>9.0</td>
      <td>3192</td>
      <td>1.037778</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Goatfell</td>
      <td>8.0</td>
      <td>2866</td>
      <td>73.217</td>
      <td>8.0</td>
      <td>2866</td>
      <td>1.227778</td>
    </tr>
  </tbody>
</table>
</div>




```python
df.dtypes
```




    Unnamed: 0     object
    dist_x        float64
    climb_x         int64
    time_x        float64
    dist_y        float64
    climb_y         int64
    time_y        float64
    dtype: object




```python
df['dist'] = df.loc[:, ['dist_x', 'dist_y']].mean(skipna=True, axis=1)
df['climb'] = df.loc[:, ['climb_x', 'climb_y']].mean(skipna=True, axis=1)
df['time'] = df.loc[:, ['time_x', 'time_y']].mean(skipna=True, axis=1)
df = df.drop(['dist_x', 'dist_y', 'climb_x', 'climb_y', 'time_x', 'time_y'], axis=1)
df.columns = ['name', 'dist', 'climb', 'time']
```


```python
df.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>dist</th>
      <th>climb</th>
      <th>time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Craig Dunain</td>
      <td>6.0</td>
      <td>900.0</td>
      <td>17.098056</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Ben Lomond</td>
      <td>8.5</td>
      <td>3131.0</td>
      <td>31.652389</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Goatfell</td>
      <td>8.0</td>
      <td>2866.0</td>
      <td>37.222389</td>
    </tr>
  </tbody>
</table>
</div>




```python

```

c89937d37888959c0e31a13c0e944527c43ca3c1
ipynb
Jupyter Notebook
labs/Lab05S_Solutions.ipynb
taotangtt/sta-663-2018
67dac909477f81d83ebe61e0753de2328af1be9c
BSD-3-Clause
2018-01-20T20:50:22.000Z
2022-02-27T23:24:21.000Z
labs/Lab05S_Solutions.ipynb
taotangtt/sta-663-2018
67dac909477f81d83ebe61e0753de2328af1be9c
BSD-3-Clause
2020-02-03T13:43:46.000Z
2020-02-03T13:43:46.000Z
labs/Lab05S_Solutions.ipynb
taotangtt/sta-663-2018
67dac909477f81d83ebe61e0753de2328af1be9c
BSD-3-Clause
2018-01-12T17:13:14.000Z
2022-03-14T20:22:46.000Z
Qwen/Qwen-72B
1. YES
2. YES