Skip to content

Commit

Permalink
HOF
Browse files Browse the repository at this point in the history
  • Loading branch information
Asabeneh committed Jul 8, 2021
1 parent 306c046 commit 0a9ffb9
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,7 @@ print('num_float', float(num_str)) # 10.6

# str to list
first_name = 'Asabeneh'
print(first_name)
print(first_name) # 'Asabeneh'
print(first_name) # 'Asabeneh'
first_name_to_list = list(first_name)
print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']
```
Expand Down
13 changes: 12 additions & 1 deletion 07_Day_Sets/07_sets.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,24 @@ st = {'item1', 'item2', 'item3', 'item4'}
st.remove('item2')
```

The pop() methods remove a random item from a list and it returns the removed item.

**Example:**

```py
fruits = {'banana', 'orange', 'mango', 'lemon'}
fruits.pop() # removes the last element from the set
fruits.pop() # removes a random item from the set

```

If we are interested in the removed item.

```py
fruits = {'banana', 'orange', 'mango', 'lemon'}
removed_item = fruits.pop()
```


### Clearing Items in a Set

If we want to clear or empty the set we use _clear_ method.
Expand Down
4 changes: 4 additions & 0 deletions 10_Day_Loops/10_loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ for iterator in string:
language = 'Python'
for letter in language:
print(letter)


for i in range(len(language)):
print(language[i])
```

- For loop with tuple
Expand Down
68 changes: 38 additions & 30 deletions 14_Day_Higher_order_functions/14_higher_order_functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> First Edition: Nov 22 - Dec 22, 2019</small>
<small>Second Edition: July, 2021</small>
</sub>
</div>
</div>
Expand All @@ -31,12 +31,15 @@
- [Python - Filter Function](#python---filter-function)
- [Python - Reduce Function](#python---reduce-function)
- [💻 Exercises: Day 14](#-exercises-day-14)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)

# 📘 Day 14

## Higher Order Functions

In python functions are treated as first class citizens, allowing you to perform the following operations on functions:
In Python functions are treated as first class citizens, allowing you to perform the following operations on functions:

- A function can take one or more functions as parameters
- A function can be returned as a result of another function
Expand All @@ -46,17 +49,17 @@ In python functions are treated as first class citizens, allowing you to perform
In this section, we will cover:

1. Handling functions as parameters
2. Returning functions as return value from other functions
3. Using python closures and decorators
2. Returning functions as return value from another functions
3. Using Python closures and decorators

### Function as a Parameter

```py
def sum_numbers(nums): # normal function
return sum(nums) # a sad function abusing the built-in sum function :<

def higher_order_function(f, *args): # function as a parameter
summation = f(*args)
def higher_order_function(f, lst): # function as a parameter
summation = f(lst)
return summation
result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5])
print(result) # 15
Expand Down Expand Up @@ -97,14 +100,13 @@ You can see from the above example that the higher order function is returning d

## Python Closures

Python allows a nested function to access the outer scope of the enclosing function. This is is known as a Closure. Let’s have a look at how closures work in Python. In Python, closure is created by nesting a function inside another encapsulating function and then returning the inner function. See the example below.
Python allows a nested function to access the outer scope of the enclosing function. This is is known as a Closure. Let us have a look at how closures work in Python. In Python, closure is created by nesting a function inside another encapsulating function and then returning the inner function. See the example below.

**Example:**

```py
def add_ten():
ten = 10

def add(num):
return num + ten
return add
Expand Down Expand Up @@ -137,7 +139,7 @@ def uppercase_decorator(function):
g = uppercase_decorator(greeting)
print(g()) # WELCOME TO PYTHON

## Lets implement the example above with a decorator
## Let us implement the example above with a decorator

'''This decorator function is a higher order function
that takes a function as a parameter'''
Expand Down Expand Up @@ -168,6 +170,7 @@ def uppercase_decorator(function):
make_uppercase = func.upper()
return make_uppercase
return wrapper

# Second decorator
def split_string_decorator(function):
def wrapper():
Expand All @@ -179,11 +182,9 @@ def split_string_decorator(function):

@split_string_decorator
@uppercase_decorator # order with decorators is important in this case - .upper() function does not work with lists

def greeting():
return 'Welcome to Python'
print(greeting()) # WELCOME TO PYTHON

```

### Accepting Parameters in Decorator Functions
Expand Down Expand Up @@ -251,7 +252,7 @@ def change_to_upper(name):
names_upper_cased = map(change_to_upper, names)
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']

# Lets apply it with a lambda function
# Let us apply it with a lambda function
names_upper_cased = map(lambda name: name.upper(), names)
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
```
Expand Down Expand Up @@ -310,7 +311,7 @@ print(list(long_names)) # ['Asabeneh']

### Python - Reduce Function

The _reduce()_ function is defined in the functools module and we should import it from this module. Like map and filter it takes two parameters, a function and an iterable. However, it doesn't return another iterable, instead it returns a single value.
The _reduce()_ function is defined in the functools module and we should import it from this module. Like map and filter it takes two parameters, a function and an iterable. However, it does not return another iterable, instead it returns a single value.
**Example:1**

```py
Expand All @@ -330,29 +331,36 @@ names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### Exercises: Level 1

1. Explain the difference between map, filter, and reduce.
2. Explain the difference between higher order function, closure and decorator
3. Define a call function before map, filter or reduce, see examples.
4. Use for loop to print each country in the countries list.
5. Use for to print each name in the names list.
6. Use for to print each number in the numbers list.
7. Use map to create a new list by changing each country to uppercase in the countries list
8. Use map to create a new list by changing each number to its square in the numbers list
9. Use map to change each name to uppercase in the names list
10. Use filter to filter out countries containing 'land'.
11. Use filter to filter out countries having exactly six characters.
12. Use filter to filter out countries containing six letters and more in the country list.
13. Use filter to filter out countries starting with an 'E'
14. Chain two or more list iterators (eg. arr.map(callback).filter(callback).reduce(callback))
15. Declare a function called get_string_lists which takes a list as a parameter and then returns a list containing only string items.
16. Use reduce to sum all the numbers in the numbers list.
17. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries
18. Declare a function called categorize_countries that returns a list of countries with some common pattern (you can find the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) in this repository as countries.js(eg 'land', 'ia', 'island', 'stan')).
19. Create a function returning a dictionary, where keys stand for starting letters of countries and values are the number of country names starting with that letter.
20. Declare a get_first_ten_countries function - it returns a list of first ten countries from the countries.js list in the data folder.
21. Declare a get_last_ten_countries function that returns the last ten countries in the countries list.

23. Use the countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) file and follow the tasks below:

### Exercises: Level 2

1. Use map to create a new list by changing each country to uppercase in the countries list
1. Use map to create a new list by changing each number to its square in the numbers list
1. Use map to change each name to uppercase in the names list
1. Use filter to filter out countries containing 'land'.
1. Use filter to filter out countries having exactly six characters.
1. Use filter to filter out countries containing six letters and more in the country list.
1. Use filter to filter out countries starting with an 'E'
1. Chain two or more list iterators (eg. arr.map(callback).filter(callback).reduce(callback))
1. Declare a function called get_string_lists which takes a list as a parameter and then returns a list containing only string items.
1. Use reduce to sum all the numbers in the numbers list.
1. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries
1. Declare a function called categorize_countries that returns a list of countries with some common pattern (you can find the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) in this repository as countries.js(eg 'land', 'ia', 'island', 'stan')).
1. Create a function returning a dictionary, where keys stand for starting letters of countries and values are the number of country names starting with that letter.
2. Declare a get_first_ten_countries function - it returns a list of first ten countries from the countries.js list in the data folder.
1. Declare a get_last_ten_countries function that returns the last ten countries in the countries list.

### Exercises: Level 3

1. Use the countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) file and follow the tasks below:
- Sort countries by name, by capital, by population
- Sort out the ten most spoken languages by location.
- Sort out the ten most populated countries.
Expand Down

0 comments on commit 0a9ffb9

Please sign in to comment.