Posts

Showing posts from July, 2019

Python - Sets

Are unordered like dictionaries. only Unique values are allowed  Supports set operations like Union and Intersect. Sets Sets  are data structures, similar to lists or dictionaries. They are created using curly braces, or the  set   function . They share some functionality with lists, such as the use of  in  to check whether they contain a particular item. num_set = {1, 2, 3, 4, 5} word_set = set(["spam", "eggs", "sausage"]) print(3 in num_set) print("spam" not in word_set) Result: >>> True False >>> To create an empty set, you must use  set() , as  {}  creates an empty  dictionary . Use discard to remove an element from a set - if element is not found it will do nothing. num_set.discard(1) Use remove to remove an element from a set - if the element is not found it will throw an error num_set.remove(1) Set Union and Intersection method to find Unique items in 2 groups or common items in tow gr...

Python - Recursion

Recursion Recursion  is a very important concept in functional programming.  The fundamental part of recursion is self-reference - functions calling themselves. It is used to solve problems that can be broken up into easier sub-problems of the same type. A classic example of a  function  that is implemented recursively is the  factorial  function , which finds the product of all positive integers below a specified number.  For example, 5! (5 factorial) is 5 * 4 * 3 * 2 * 1 (120). To implement this recursively, notice that 5! = 5 * 4!, 4! = 4 * 3!, 3! = 3 * 2!, and so on. Generally, n! = n * (n-1)!.  Furthermore, 1! = 1. This is known as the  base case , as it can be calculated without performing any more factorials.  Below is a recursive implementation of the factorial  function . def factorial (x): if x == 1: return 1 else: return x * factorial (x-1) print(factorial(5)) Result: >>> 120 >...

Python Comments- Multi-Line comments

Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Creating a Comment Comments start with a  # , and Python will ignore them: Example #This is a comment  print ( "Hello, World!" ) Multi-Line Comments Python does not really have a syntax for multi-line comments. Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it: Example "" " This is a comment written in  more than just one line " "" print ( "Hello, World!" )

Python Indentations

Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important. Python uses indentation to indicate a block of code. Example if   5  >  2 :    print ( "Five is greater than two!" ) Python will give you an error if you skip the indentation: Example if   5  >  2 : print ( "Five is greater than two!" )

Python - Decorators - Nested Functions - Extend Functions

Decorators Decorators  provide a way to modify functions using other functions.  This is ideal when you need to extend the functionality of functions that you don't want to modify. Example: def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decorated = decor(print_text) decorated() We defined a  function  named  decor  that has a single  parameter   func . Inside  decor , we defined a nested  function  named  wrap . The  wrap  function  will print a  string , then call  func() , and print another  string . The  decor  function  returns the  wrap  function  as its result. We could say that the  variable   decorated  is a decorated version of  print_text  - it's  print_text  plus something.  In fact, if we wrote a useful...

Python - Generators

Generators Generators  are a type of  iterable , like lists or tuples.  Unlike lists, they don't allow indexing with arbitrary indices, but they can still be iterated through with  for  loops.  They can be created using functions and the  yield   statement. Example: def countdown(): i=5 while i > 0: yield i i -= 1 for i in countdown(): print(i) Result: >>> 5 4 3 2 1 The  yield   statement is used to define a  generator , replacing the return of a  function  to provide a result to its caller without destroying local variables. Due to the fact that they  yield   one item at a time, generators don't have the memory restrictions of lists.  In fact, they can be  infinite! def infinite_sevens(): while True: yield 7 for i in infinite_sevens(): print(i) Result: >>> 7 7 7 7 7 7 7 ... In short,  generators  allow you to declare...

Python - Map and Filter

map The built-in functions  map  and  filter  are very useful higher-order functions that operate on lists (or similar objects called  iterables ).  The  function   map  takes a  function  and an  iterable  as arguments, and returns a new  iterable  with the  function  applied to each  argument .  Example: def add_five(x): return x + 5 nums = [11, 22, 33, 44, 55] result = list( map (add_five, nums)) print(result) Result: >>> [16, 27, 38, 49, 60] >>> We could have achieved the same result more easily by using  lambda   syntax. nums = [11, 22, 33, 44, 55] result = list(map( lambda x: x+5 , nums)) print(result) To convert the result into a list, we used  list  explicitly. filter The  function   filter  filters an  iterable  by removing items that don't match a  predicate  (a  function that return...

Python - Lambdas

Lambdas Creating a  function  normally (using  def ) assigns it to a  variable  automatically.  This is different from the creation of other objects - such as strings and integers - which can be created on the fly, without assigning them to a  variable .  The same is possible with functions, provided that they are created using  lambda  syntax. Functions created this way are known as  anonymous . This approach is most commonly used when passing a simple  function  as an  argument  to another  function . The syntax is shown in the next example and consists of the  lambda   keyword followed by a list of arguments, a colon, and the expression to evaluate and return. def my_func(f, arg): return f(arg) my_func( lambda x: 2*x*x, 5) Lambda functions get their name from   lambda  calculus , which is a model of computation invented by Alonzo Church. Lambda functions aren't as powerfu...

Python - Functional Programming - Pure Function - Higher Order Functions - Memoization

Image
Functional Programming 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 . i.e. functions as objects.  In mathematics and computer science, a  higher-order function  is a function that does at least one of the following: takes one or more functions as arguments (i.e. procedural parameters), returns a function as its result. All other functions are  first-order functions . In mathematics, higher-order functions are also termed  operators  or  functionals . The  differential operator  in  calculus  is a common example, since it maps a function to its  derivative , also a function. Higher-order functions should not be confused with other uses of the word "functor" throughout mathematics, see  Functor (disambiguation) . In the untyped  lambda...