# 1. Numbers

##  Creating formulas

Write the following mathematical formula in Python:

\begin{align}
 result = 6a^3 - \frac{8b^2 }{4c} + 11
\end{align}

```python
a = 2
b = 3
c = 2
```

> write your formula as 
```python
result = 
```

It must verify
```python
>>> assert result == 50
```

## Floating point pitfalls

Show that `0.1 + 0.2 == 0.3`

# 2. Lists

## Fill the missing pieces

Fill the `____` parts of the code below.

```python
# Let's create an empty list
my_list = ____

# Let's add some values
my_list.____('Python')
my_list.____('is ok')
my_list.____('sometimes')

# Let's remove 'sometimes'
my_list.____('sometimes')

# Let's change the second item
my_list[____] = 'is neat'
```

Let's verify that it's correct
```python
>>> assert my_list == ['Python', 'is neat']
```

## Create a new list without modifiying the original one

```python
original = ['I', 'am', 'learning', 'hacking', 'in']
```

> Your implementation here
```python
modified = 
```

```python
>>> assert original == ['I', 'am', 'learning', 'hacking', 'in']
>>> assert modified == ['I', 'am', 'learning', 'lists', 'in', 'Python']
```

## Create a merged sorted list

```python
list1 = [6, 12, 5]
list2 = [6.2, 0, 14, 1]
list3 = [0.9]
```

> Your implementation here
```python
my_list =
```

```python
>>> assert my_list == [14, 12, 6.2, 6, 5, 1, 0.9, 0]
```

# 3. Dictionaries

## Populating a dictionary

Create a dictionary by using all the given variables.

```python
first_name = 'John'
last_name = 'Doe'
favorite_hobby = 'Python'
sports_hobby = 'gym'
age = 82
```

> Your implementation
```python
my_dict =
```

```python
>>> assert my_dict == {
        'name': 'John Doe',
        'age': 82,
        'hobbies': ['Python', 'gym']
    }
```

## Accessing and merging dictionaries

Combine `dict1`, `dict2`, and `dict3` into `my_dict`. In addition, get the value of `special_key` from `my_dict` into a `special_value` variable. Note that original dictionaries should stay untouched and `special_key` should be removed from `my_dict`.

```python
dict1 = dict(key1='This is not that hard', key2='Python is still cool')
dict2 = {'key1': 123, 'special_key': 'secret'}
# This is also a away to initialize a dict (list of tuples) 
dict3 = dict([('key2', 456), ('keyX', 'X')])
```

> Your impelementation
```python
my_dict = 
special_value = 
```

```python
>>> assert my_dict == {'key1': 123, 'key2': 456, 'keyX': 'X'}
>>> assert special_value == 'secret'

>>> # Let's check that the originals are untouched
>>> assert dict1 == {
        'key1': 'This is not that hard',
        'key2': 'Python is still cool'
    }
>>> assert dict2 == {'key1': 123, 'special_key': 'secret'}
>>> assert dict3 == {'key2': 456, 'keyX': 'X'}
```

# 4. Functions

## Fill the missing pieces of the `count_even_numbers` function

Fill `____` pieces of the `count_even_numbers` implemention in order to pass the assertions. You can assume that `numbers` argument is a list of integers.

```python
____ count_even_numbers(numbers):
    count = 0
    for num in ____:
        if ____ % 2 == ____:
            count += ____
    _____ _____
```

```python
>>> assert count_even_numbers([1, 2, 3, 4, 5, 6]) == 3
>>> assert count_even_numbers([1, 3, 5, 7]) == 0
>>> assert count_even_numbers([-2, 2, -10, 8]) == 4
```

## Searching for wanted people

Implement `find_wanted_people` function which takes a list of names (strings) as argument. The function should return a list of names which are present both in `WANTED_PEOPLE` and in the name list given as argument to the function.

```python
WANTED_PEOPLE = ['John Doe', 'Clint Eastwood', 'Chuck Norris']
```

> Your implementation here

```python
>>> people_to_check1 = ['Donald Duck', 'Clint Eastwood', 'John Doe', 'Barack Obama']
>>> wanted1 = find_wanted_people(people_to_check1)
>>> assert len(wanted1) == 2
>>> assert 'John Doe' in wanted1
>>> assert 'Clint Eastwood'in wanted1

>>> people_to_check2 = ['Donald Duck', 'Mickey Mouse', 'Zorro', 'Superman', 'Robin Hood']
>>> wanted2 = find_wanted_people(people_to_check2)
>>> assert wanted2 == []
```

## Counting average length of words in a sentence

Create a function `average_length_of_words` which takes a string as an argument and returns the average length of the words in the string. You can assume that there is a single space between each word and that the input does not have punctuation. The result should be rounded to one decimal place (hint: see [`round`](https://docs.python.org/3/library/functions.html#round)).

> Your implementation here

```python
>>> assert average_length_of_words('only four lett erwo rdss') == 4
>>> assert average_length_of_words('one two three') == 3.7
>>> assert average_length_of_words('one two three four') == 3.8
>>> assert average_length_of_words('') == 0
```

# 5. Strings

## Fill missing pieces

Fill `____` pieces below to have correct values for `lower_cased`, `stripped` and `stripped_lower_case` variables.

```python
original = ' Python strings are COOL! '
lower_cased = original._____
stripped = ____.strip()
stripped_lower_cased = original._____._____
```

Let's verify that the implementation is correct by running the cell below. `assert` will raise `AssertionError` if the statement is not true.  

```python
>>> assert lower_cased == ' python strings are cool! '
>>> assert stripped == 'Python strings are COOL!'
>>> assert stripped_lower_cased == 'python strings are cool!'
```

## Prettify ugly string

Use `str` methods to convert `ugly` to wanted `pretty`.

```python
ugly = ' tiTle of MY new Book\n\n'
```

> Your implementation:
```python
pretty = 'TODO'
```

Let's make sure that it does what we want. `assert` raises [`AssertionError`](https://docs.python.org/3/library/exceptions.html#AssertionError) if the statement is not `True`.

```python
>>> print('pretty: {}'.format(pretty))
>>> assert pretty == 'Title Of My New Book'
```

## Format string based on existing variables

Create `sentence` by using `verb`, `language`, and `punctuation` and any other strings you may need.

```python
verb = 'is'
language = 'Python'
punctuation = '!'
```

> Your implementation:
```python
sentence = 'TODO'
```

```python
>>> print('sentence: {}'.format(sentence))
>>> assert sentence == 'Learning Python is fun!'
```

# 6. For Loops

## Fill the missing pieces

Fill the `____` parts in the code below.

```python
words = ['PYTHON', 'JOHN', 'chEEse', 'hAm', 'DOE', '123']
upper_case_words = []

for ____ in words:
    if ____.isupper():
        ____.append(____)

        
>>> assert upper_case_words == ['PYTHON', 'JOHN', 'DOE']        
```

## Calculate the sum of dict values

Calculate the sum of the values in `magic_dict` by taking only into account numeric values (hint: see [isinstance](https://docs.python.org/3/library/functions.html#isinstance)). 

```python
magic_dict = dict(val1=44, val2='secret value', val3=55.0, val4=1)
```

> Your implementation
```python
sum_of_values =     
```

```python
>>> assert sum_of_values == 100
```

## Create a list of strings based on a list of numbers

The rules:
* If the number is a multiple of five and odd, the string should be `'five odd'`
* If the number is a multiple of five and even, the string should be `'five even'`
* If the number is odd, the string is `'odd'`
* If the number is even, the string is `'even'`

```python
numbers = [1, 3, 4, 6, 81, 80, 100, 95]
```

> Your implementation
```python
my_list =
```

```python
>>> assert my_list == ['odd', 'odd', 'even', 'even', 'odd', 'five even', 'five even', 'five odd']
```

# 7. Conditionals

## `if-elif-else`

Fill missing pieces (`____`) of the following code such that prints make sense.

```python
name = 'John Doe'

if ____:
    print('Name "{}" is more than 20 chars long'.format(name))
    length_description = 'long'
elif ____:
    print('Name "{}" is more than 15 chars long'.format(name))
    length_description = 'semi long'
elif ____:
    print('Name "{}" is more than 10 chars long'.format(name))
    length_description = 'semi long'
elif ____:
    print('Name "{}" is 8, 9 or 10 chars long'.format(name))
    length_description = 'semi short'
else:
    print('Name "{}" is a short name'.format(name))
    length_description = 'short'
    
>>> assert length_description == 'semi short'    
```

# 8. Classes

## Fill the missing pieces of the `Calculator` class

Fill `____` pieces of the `Calculator` implemention in order to pass the assertions.

```python
class Calculator:
    def __init__(self, var1, ____):
        self.____ = var1
        self.____ = _____
    
    def calculate_power(self):
        return self.____ ** ____.____
    
    def calculate_sum(____, var3):
        return ____.____ + ____.____ + var3
```

```python
>>> calc = Calculator(2, 3)
>>> assert calc.calculate_power() == 8
>>> assert calc.calculate_sum(4) == 9        
```

## Finalize `StringManipulator` class

Fill `____` pieces and create implementation for `stripped_title()`.

```python
class StringManipulator:
    """____"""
    
    category = ____
    
    def __init__(self, original):
        self.string = ____
        
    def reverse_words(self):
        words = self.string.____
        self.string = ' '.join(reversed(____))
        
    def make_title(self):
        # Create implementation for this
        
    def get_manipulated(____):
        return self._____
```

```python
>>> assert StringManipulator.__doc__ == 'Docstring of StringManipulator'
>>> assert StringManipulator.category == 'Manipulator'

>>> str_manip = StringManipulator('cOOL pyThON')

>>> str_manip.reverse_words()
>>> assert str_manip.get_manipulated() == 'pyThON cOOL'

>>> str_manip.make_title()
>>> assert str_manip.get_manipulated() == 'Python Cool'        
```

## Create `Dog` class

Create `Dog` class which has the following specification:

* Dogs consume their energy by barking and gain energy by sleeping
* A fresh `Dog` instance has 10 units of energy
* `Dog` has a method `sleep` which gives 2 units of energy
* `Dog` has a method `bark` which consumes 1 unit of energy
* `Dog` has a method `get_energy` which returns the amount of energy left 

```python
class Dog:
    # Your implementation here
```

```python
>>> doge = Dog()
>>> assert doge.get_energy() == 10

>>> doge.bark()
>>> doge.bark()
>>> doge.bark()
>>> assert doge.get_energy() == 7

>>> doge.sleep()
>>> assert doge.get_energy() == 9

>>> another_doge = Dog()
>>> assert another_doge.get_energy() == 10  
```

# 9. Exceptions

# 10. File IO

# 11. Standard Library

## Collections

### NamedTuple


#### Creating a namedtuple

Create a namedtuple `Car` which has fields `price`, `mileage`, and `brand`. 

> Your implemenation here

```python
>>> car1 = Car(25000, 2000, 'BMW')
>>> assert car1.price == 25000
>>> assert car1.mileage == 2000
>>> assert car1.brand == 'BMW'
>>> assert isinstance(car1, tuple)

>>> # Note that indexing works also!
>>> # This means that if you change a tuple into a namedtuple,
>>> # the change will be backwards compatible.
>>> assert car1[2] == 'BMW'

>>> print('All good!')
```



### urllib

#### example 1

Below you can see `get_wiki_article` function which is a very simple implementation for fetching an article from wikipedia. Your task is to mock it's implementation such that it's going to always return `'Python is cool!'`. However, note that you should be able to check which argument is given to `urlopen` when `get_wiki_article` is called.

**Note**: `get_content_of_url` uses [`urrlib`](https://docs.python.org/3/library/urllib.html#module-urllib), which is part of the Standard Library, for creating a HTTP request. Usually it's preferable to use [`requests`](http://docs.python-requests.org/en/master/) library (not part of the Standard Library) for such operations. Actually, `requests` uses `urllib` under the hood so it's good to know what's happening when you start using `requests` - or maybe you have already used it.


```python
from urllib.request import urlopen

def get_wiki_article(name):
    url = 'https://en.wikipedia.org/wiki/{}'.format(name)
    response = urlopen(url)
    content = str(response.read())
    return content
```

> Your implementation here

```python
>>> article = 'Python_(programming_language)'
>>> res = get_wiki_article(article)
>>> assert 'Guido van Rossum' not in res, 'Guido is still there!'
>>> assert res == 'Python is cool!'
>>> urlopen.assert_called_with('https://en.wikipedia.org/wiki/Python_(programming_language)')

>>> print('All good!')
```






















```python
# css style
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```




<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>
<style>
    @font-face {
        font-family: "Computer Modern";
        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
    }
    div.cell{
        width:600px;
        margin-left:16% !important;
        margin-right:auto;
    }
    h1 {
        font-family: 'Alegreya Sans', sans-serif;
    }
    h2 {
        font-family: 'Fenix', serif;
    }
    h3{
		font-family: 'Fenix', serif;
        margin-top:12px;
        margin-bottom: 3px;
       }
	h4{
		font-family: 'Fenix', serif;
       }
    h5 {
        font-family: 'Alegreya Sans', sans-serif;
    }	   
    div.text_cell_render{
        font-family: 'Alegreya Sans',Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        line-height: 135%;
        font-size: 120%;
        width:600px;
        margin-left:auto;
        margin-right:auto;
    }
    .CodeMirror{
            font-family: "Source Code Pro";
			font-size: 90%;
    }
/*    .prompt{
        display: None;
    }*/
    .text_cell_render h1 {
        font-weight: 200;
        font-size: 50pt;
		line-height: 100%;
        color:#054BCD;
        margin-bottom: 0.5em;
        margin-top: 0.5em;
        display: block;
    }	
    .text_cell_render h5 {
        font-weight: 300;
        font-size: 16pt;
        color: #054BCD;
        font-style: italic;
        margin-bottom: .5em;
        margin-top: 0.5em;
        display: block;
    }

    .warning{
        color: rgb( 240, 20, 20 )
        }  
</style>






```python

```

b902f8896f6da2d405d02e7f22883b788a181e93
ipynb
Jupyter Notebook
M3/codes/Exercises.ipynb
ratnania/UM6P-MHACS-EX-2020
da57f6c7fdfdd094c20c7a0101b6c70ef0b056f4
MIT
2020-01-03T03:49:20.000Z
2020-07-29T21:51:11.000Z
M3/codes/Exercises.ipynb
ratnania/UM6P-MHACS-EX-2020
da57f6c7fdfdd094c20c7a0101b6c70ef0b056f4
MIT
M3/codes/Exercises.ipynb
ratnania/UM6P-MHACS-EX-2020
da57f6c7fdfdd094c20c7a0101b6c70ef0b056f4
MIT
Qwen/Qwen-72B
1. YES
2. YES