diff --git a/14_Day/14_higher_order_function.md b/14_Day/14_higher_order_function.md index 8eeed36..7fba2e8 100644 --- a/14_Day/14_higher_order_function.md +++ b/14_Day/14_higher_order_function.md @@ -19,13 +19,13 @@ ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) - [📘 Day 14](#%f0%9f%93%98-day-14) - [Higher Order Functions](#higher-order-functions) - - [Function as a parameter](#function-as-a-parameter) - - [Function as a return value](#function-as-a-return-value) - - [Python closures](#python-closures) - - [Python decorators](#python-decorators) + - [Function as a Parameter](#function-as-a-parameter) + - [Function as a Return Value](#function-as-a-return-value) + - [Python Closures](#python-closures) + - [Python Decorators](#python-decorators) - [Creating Decorators](#creating-decorators) - [Applying Multiple Decorators to a Single Function](#applying-multiple-decorators-to-a-single-function) - - [Accepting parameters in Decorator Functions](#accepting-parameters-in-decorator-functions) + - [Accepting Parameters in Decorator Functions](#accepting-parameters-in-decorator-functions) - [Built-in Higher Order Functions](#built-in-higher-order-functions) - [Python - Map Function](#python---map-function) - [Python - Filter Function](#python---filter-function) @@ -49,11 +49,11 @@ In this section, we will cover: 2. Returning functions as return value from other functions 3. Using python closures and decorators -### Function as a parameter +### Function as a Parameter ```py def sum_numbers(nums): # normal function - return sum(nums) + 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) @@ -62,7 +62,7 @@ result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5]) print(result) # 15 ``` -### Function as a return value +### Function as a Return Value ```py def square(x): # a square function @@ -72,14 +72,12 @@ def cube(x): # a cube function return x ** 3 def absolute(x): # an absolute value function - if x == 0: + if x >= 0: return x - elif x < 1: - return -(x) else: - return x + return -(x) -def higher_order_function(type): # a higher order function returning function +def higher_order_function(type): # a higher order function returning a function if type == 'square': return square elif type == 'cube': @@ -97,9 +95,9 @@ print(result(-3)) # 3 You can see from the above example that the higher order function is returning different functions depending on the passed parameter -## Python closures +## 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 works 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’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. **Example:** @@ -116,13 +114,13 @@ print(closure_result(5)) # 15 print(closure_result(10)) # 20 ``` -## Python decorators +## Python Decorators A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. ### Creating Decorators -To create a decorator function, we need an outer function, inner wrapper function. +To create a decorator function, we need an outer function with an inner wrapper function. **Example:** @@ -139,10 +137,10 @@ def uppercase_decorator(function): g = uppercase_decorator(greeting) print(g()) # WELCOME TO PYTHON -## Lets implement the above to a decorator +## Lets implement the example above with a decorator -'''This decorator function is a higher order -which is take function as a parameter''' +'''This decorator function is a higher order function +that takes a function as a parameter''' def uppercase_decorator(function): def wrapper(): func = function() @@ -161,7 +159,7 @@ print(greeting()) # WELCOME TO PYTHON ```py '''These decorator functions are higher order functions -which take function as parameters''' +that take functions as parameters''' # First Decorator def uppercase_decorator(function): @@ -179,15 +177,16 @@ def split_string_decorator(function): return wrapper -@uppercase_decorator @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 +### Accepting Parameters in Decorator Functions Most of the time we need our functions to take parameters, so we might need to define a decorator that accepts parameters. @@ -200,7 +199,7 @@ def decorator_with_parameters(function): @decorator_with_parameters def print_full_name(first_name, last_name, country): - print("I am {} {}. I love teaching".format( + print("I am {} {}. I love to teach.".format( first_name, last_name, country)) print_full_name("Asabeneh", "Yetayeh",'Finland') @@ -208,12 +207,12 @@ print_full_name("Asabeneh", "Yetayeh",'Finland') ## Built-in Higher Order Functions -Some of the builtin higher order function which we cover in the part are _map()_, _filter_, and _reduce_. -Lambda function can be passed a parameter and the best use case of lambda function is in function like map, filter and reduce. +Some of the built-in higher order functions that we cover in this part are _map()_, _filter_, and _reduce_. +Lambda function can be passed as a parameter and the best use case of lambda functions is in functions like map, filter and reduce. ### Python - Map Function -The map() function is a built-in function which takes a function and iterable as parameter. +The map() function is a built-in function that takes a function and iterable as parameters. ```py # syntax @@ -257,11 +256,11 @@ names_upper_cased = map(lambda name: name.upper(), names) print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM'] ``` -What actually map do is mapping a list. For instance it changes the names to upper case and return a new list. +What actually map does is iterating over a list. For instance, it changes the names to upper case and returns a new list. ### Python - Filter Function -The filter() function calls the specified function which returns boolean for each item of the specified iterable (list). It filters the items which the satisfied with the filtering criteria. +The filter() function calls the specified function which returns boolean for each item of the specified iterable (list). It filters the items that satisfy the filtering criteria. ```py # syntax @@ -311,7 +310,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 doesn't return another iterable, instead it returns a single value. **Example:2** @@ -333,28 +332,27 @@ numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` 1. Explain the difference between map, filter, and reduce. -1. Explain the difference between higher order function, closure and decorator -1. Define a call function before map, filter or reduce, see examples. -1. Use for loop to print each country in the countries list. -1. Use for to print each name in the names list. -1. Use for to print each number in the numbers list. -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 square in the numbers list -1. Use map to change to 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 six character. -1. Use filter to filter out countries containing six letters and more in the country list. -1. Use filter to filter out country start with '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 an list as a parameter and then returns an list only with 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 which returns an list of countries which have some common pattern(you 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 which return a list of dictionary, which is the letter and the number of times the letter used to start a name of a country. -1. Declare a get_first_ten_countries function and return an list of ten countries from the countries.js list in the data folder. -1. Declare a get_last_ten_countries function which which returns the last ten countries in the countries list. -1. Find out which letter is used many times as initial for a country name from the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py)(eg. Finland, Fiji, France etc) -1. Use the countries_data.py file information, in the data folder. +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: - Sort countries by name, by capital, by population - Sort out the ten most spoken languages by location. - Sort out the ten most populated countries.