Functional programming Python

Functional programming is a style of programming that (as the name suggests) is based around functions. 
A key part of functional programming is higher-order functions.

def apply_twice(func, arg):
   return func(func(arg))

def add_five(x):
   return x + 5


print(apply_twice(add_five, 10))



> anonymous functions called lambdas
#named function
def polynomial(x):
return x**2 + 5*x + 4
print(polynomial(-4))

#lambda
print((lambda x: x**2 + 5*x + 4) (-4))

> lambda function
double = lambda x: x * 2
print(double(7))

-----------------------------


The built-in functions map and filter are very useful higher-order functions that operate on lists 

>Map

def add_five(x):
return x + 5

nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))


> Filter
The function filter filters an iterable by removing items that don't match a predicate 


nums = [11, 22, 33, 44, 55]
res = list(filter(lambda x: x%2==0, nums))

---------------

Generators

>Generators are a type of iterable, like lists or tuples. 
>They don't allow indexing with arbitrary indices. 
>Generators don't have the memory restrictions. 
>Finite generators can be converted into lists by passing them as arguments to the list

def countdown():
i=5
while i > 0:
yield i
i -= 1

for i in countdown():
print(i)

print(list(countdown()))


Decorators
Decorators provide a way to modify functions using other functions. 

def print_text():
print("Hello world!")

print_text = decor(print_text)

--can also be achieved by
@decor
def print_text():
print("Hello world!")


Recursion
functions calling themselves

def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)

print(factorial(5))


> error occur for infinite loops
RuntimeError: maximum recursion depth exceeded

-----------


Sets


Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set.

> They can't be indexed.
They are unordered.
>They cannot contain duplicate elements.
> add(value)
> remove(value)
> pop() remove last value

num_set = {1, 2, 3, 4, 5}
word_set = set(["spam", "eggs", "sausage"])


---------------

Sets

Sets can be combined using mathematical operations.
The union operator | combines two sets to form a new one containing items in either. 
The intersection operator & gets items only in both. 
The difference operator - gets items in the first set but not in the second. 
The symmetric difference operator ^ gets items in either set, but not both.

first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}

print(first | second)
print(first & second)
print(first - second)
print(second - first)
print(first ^ second)


>>>
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{4, 5, 6}
{1, 2, 3}
{8, 9, 7}
{1, 2, 3, 7, 8, 9}
>>>


-----------

Data Structures

Python supports the following data structures: listsdictionariestuplessets.

When to use a dictionary:
- When you need a logical association between a key:value pair.
- When you need fast lookup for your data, based on a custom key.
- When your data is being constantly modified. Remember, dictionaries are mutable.

When to use the other types:
- Use lists if you have a collection of data that does not need random access. Try to choose lists when you need a simple, iterable collection that is modified frequently.
- Use a set if you need uniqueness for the elements. 
- Use tuples when your data cannot change. 



--------------

itertools

The module itertools is a standard library

One type of function it produces is infinite iterators. 
count counts up infinitely from a value. 
cycle infinitely iterates through an iterable (for instance a list or string). 
repeat repeats an object, either infinitely or a specific number of times.

takewhile - takes items from an iterable while a predicate function remains true;
chain - combines several iterables into one long one; 
accumulate - returns a running total of values in an iterable.



from itertools import accumulate, takewhile
nums = list(accumulate(range(8)))
print(nums)
print(list(takewhile(lambda x: x<= 6, nums)))


>>>
[0, 1, 3, 6, 10, 15, 21, 28]
[0, 1, 3, 6]
>>>


letters = ("A", "B")
print(list(product(letters, range(2))))
print(list(permutations(letters)))


>>>
[('A', 0), ('A', 1), ('B', 0), ('B', 1)]
[('A', 'B'), ('B', 'A')]
>>>


---------------

Function Arguments

Python allows to have function with varying number of arguments.
accessible as the tuple args in the body of the function. 

def function(named_arg, *args):
print(named_arg)
print(args)
function(1, 2, 3, 4, 5)


>>>
1
(2, 3, 4, 5)
>>>

Default Values


def function(x, y, food="spam"):
print(food)



**kwargs (standing for keyword arguments) allows you to handle named arguments that you have not defined in advance.

def my_func(x, y=7, *args, **kwargs):
print(kwargs)

my_func(2, 3, 4, 5, 6, a=7, b=8)


>>>
{'a': 7, 'b': 8}
>>>


------------------------

Tuple Unpacking

numbers = (1, 2, 3)
a, b, c = numbers


> an asterisk (*) takes all values from the iterable that are left over 
a, b, *c, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(d


>>>
1
2
[3, 4, 5, 6, 7, 8]
9
>>>


------------

Ternary Operator

a = 7
b = 1 if a >= 5 else 42
print(b) gives 1



----------------

__main__

def function():
print("This is a module function")

if __name__=="__main__":
print("This is a script")


>>>
This is a script
>>>



Major 3rd-Party Libraries

Django
CherryPy
Flask

-----------------

Thanks for Solo learning
https://www.sololearn.com/Play/Python

Share this

Related Posts

Previous
Next Post »