# 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
res = []
x = 0.1
r = 4.0
for i in range(10):
    res.append(x)
    x = r*x*(1-x)
print(res)
```

    [0.1, 0.36000000000000004, 0.9216, 0.28901376000000006, 0.8219392261226498, 0.5854205387341974, 0.970813326249438, 0.11333924730376121, 0.4019738492975123, 0.9615634951138128]


**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):
    if b==0: return a
    else: return gcd(b,a%b)
gcd(5797,190978)
```




    17




```python
input = [24, 48, 60, 120, 8]
def gcd_collection(input):
    prev = gcd(input[0],input[1])
    for i in range(2,len(input)):
        curr = gcd(prev,input[i])
        prev = curr
    return curr
gcd_collection(input)
```




    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
import numpy as np
import scipy.linalg as la
y = np.array([1,2,3,4])
x1 = np.array([1,2,3,4]).reshape(4,1)
x2 = np.array([2,3,4,5]).reshape(4,1)
x0 = np.ones(4).reshape(4,1)
X = np.c_[x0,x1,x2]
la.lstsq(X,y)
```




    (array([-0.33333333,  0.66666667,  0.33333333]),
     array([], dtype=float64),
     2,
     array([9.34413269, 0.82896583, 0.        ]))



**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
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
r.data('mtcars')
mtcars = r['mtcars']
mtcars.groupby('gear').mean()[['wt','mpg']]
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</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
import seaborn as sns
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
r.data('iris')
iris = r['iris']
g = sns.lmplot(x="Sepal.Length", y="Petal.Length", hue = 'Species', data = iris)
```

**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(l):
    if not isinstance(l,list):
        print('Not a list')
        return None
    else:
        
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]]




```python
def flatten(l):
    res = []
    for element in l:
        if isinstance(element, list):
            for item in flatten(element):
                res.append(item)
        else:
            res.append(element)
    return res
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
matrix = np.fromfunction(lambda i,j: np.where((i==j) | (j==0), 1, 0), (11,11), dtype='int')
for i in range(2,11):
    for j in range(1,11):
        matrix[i,j] = matrix[i-1,j]+matrix[i-1,j-1]
matrix
```




    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]])



**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
url1 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills.csv"
url2 = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/DAAG/hills2000.csv"
data1 = pd.read_csv(url1)
data2 = pd.read_csv(url2)
data = pd.merge(data1,data2,on='Unnamed: 0')
data.drop('timef',axis=1)
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</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>
    <tr>
      <th>3</th>
      <td>Scolty</td>
      <td>5.0</td>
      <td>800</td>
      <td>29.750</td>
      <td>5.0</td>
      <td>800</td>
      <td>0.495833</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Traprain</td>
      <td>6.0</td>
      <td>650</td>
      <td>39.750</td>
      <td>6.5</td>
      <td>650</td>
      <td>0.623889</td>
    </tr>
    <tr>
      <th>5</th>
      <td>Dollar</td>
      <td>5.0</td>
      <td>2000</td>
      <td>43.050</td>
      <td>6.0</td>
      <td>2000</td>
      <td>0.638333</td>
    </tr>
    <tr>
      <th>6</th>
      <td>Lomonds</td>
      <td>9.5</td>
      <td>2200</td>
      <td>65.000</td>
      <td>9.0</td>
      <td>2200</td>
      <td>1.053056</td>
    </tr>
    <tr>
      <th>7</th>
      <td>Black Hill</td>
      <td>4.5</td>
      <td>1000</td>
      <td>17.417</td>
      <td>4.0</td>
      <td>600</td>
      <td>0.447778</td>
    </tr>
    <tr>
      <th>8</th>
      <td>Meall Ant-Suidhe</td>
      <td>3.5</td>
      <td>1500</td>
      <td>27.900</td>
      <td>3.5</td>
      <td>1500</td>
      <td>0.465000</td>
    </tr>
    <tr>
      <th>9</th>
      <td>Creag Dubh</td>
      <td>4.0</td>
      <td>2000</td>
      <td>26.217</td>
      <td>3.0</td>
      <td>1223</td>
      <td>0.463889</td>
    </tr>
    <tr>
      <th>10</th>
      <td>Criffel</td>
      <td>6.5</td>
      <td>1750</td>
      <td>50.500</td>
      <td>7.0</td>
      <td>1800</td>
      <td>0.793333</td>
    </tr>
    <tr>
      <th>11</th>
      <td>Ben Nevis</td>
      <td>10.0</td>
      <td>4400</td>
      <td>85.583</td>
      <td>10.0</td>
      <td>4400</td>
      <td>1.426111</td>
    </tr>
    <tr>
      <th>12</th>
      <td>Knockfarrel</td>
      <td>6.0</td>
      <td>600</td>
      <td>32.383</td>
      <td>5.0</td>
      <td>1200</td>
      <td>0.623333</td>
    </tr>
    <tr>
      <th>13</th>
      <td>Two Breweries</td>
      <td>18.0</td>
      <td>5200</td>
      <td>170.250</td>
      <td>18.0</td>
      <td>4900</td>
      <td>2.565833</td>
    </tr>
  </tbody>
</table>
</div>



d14601298a36bafa77c06637d3106f2b2933e8c1
ipynb
Jupyter Notebook
labs/Lab05S-Zhechang Yang.ipynb
ZhechangYang/STA663
0dcf48e3e7a2d1f698b15e84946e44344b8153f5
BSD-3-Clause
labs/Lab05S-Zhechang Yang.ipynb
ZhechangYang/STA663
0dcf48e3e7a2d1f698b15e84946e44344b8153f5
BSD-3-Clause
labs/Lab05S-Zhechang Yang.ipynb
ZhechangYang/STA663
0dcf48e3e7a2d1f698b15e84946e44344b8153f5
BSD-3-Clause
Qwen/Qwen-72B
1. YES
2. YES