0% found this document useful (0 votes)
19 views

App Unit 4

APP unit 4 notes, high quality study material.

Uploaded by

lasavop349
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

App Unit 4

APP unit 4 notes, high quality study material.

Uploaded by

lasavop349
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 4

Pythonic Programming Paradigm


Functional Programming Paradigm: Concepts; Pure Function and Built-in Higher-
Order Functions; Logic Programming Paradigm: Structures, Logic, and Control;
Parallel Programming Paradigm: Shared and Distributed memory; Multi-Processing
– Ipython; Network Programming Paradigm: Socket; Socket Types; Creation and
Configuration of Sockets in TCP / UDP – Client / Server Model.
Functional Programming
• Functional programming treats computation as the evaluation of
mathematical functions.
• It emphasizes immutability, pure functions, higher-order functions,
and declarative programming.
• Functional programming avoids mutable state and emphasizes data
transformations.
• Languages like Haskell, Lisp, and Scala support functional
programming.
• Functional programming is another declarative programming
paradigm that treats computation as the evaluation of mathematical
functions.
Functional Programming (Cont..)
• The functional paradigm is popular because it offers several
advantages over other programming paradigms.
• Functional code is:
• High level: You’re describing the result you want rather than
explicitly specifying the steps required to get there. Single statements
tend to be concise but pack a lot of punch.
• Transparent: The behavior of a pure function depends only on its
inputs and outputs, without intermediary values. That eliminates the
possibility of side effects, which facilitates debugging.
• Parallelizable: Routines that don’t cause side effects can more
easily run in parallel with one another.
How Python Support Functional
Programming?
• To support functional programming, it’s useful if a function in a given
programming language has two abilities:
• To take another function as an argument
• To return another function to its caller
• Everything in a Python program is an object.
• All objects in Python have more or less equal stature, and functions
are no exception.
• In Python, functions are first-class citizens, means functions have the
same characteristics as values like strings and numbers.
• Anything you would expect to be able to do with a string or number
you can do with a function as well.
Concepts of Functional Programming
Pure Functions: These functions have two main properties.
• First, they always produce the same output for the same arguments
irrespective of anything else.
• Secondly, they have no side-effects i.e. they do modify any argument
or global variables or output something.
Recursion: There are no “for” or “while” loop in functional languages.
Iteration in functional languages is implemented through recursion.
Concepts of Functional
Programming(Cont..)
Functions are First-Class and can be Higher-Order: First-class functions
are treated as first-class variable.

• The first-class variables can be passed to functions as a parameter,


can be returned from functions or stored in data structures.

Variables are Immutable: In functional programming, it is not possible


to modify a variable after it’s been initialized.

• Possible to create new variables – but can’t modify existing variables.


Pure Functions
Pure functions have two properties.
• First, It always produces the same output for the same arguments. For
example, 3+7 will always be 10 no matter what.
• It does not change or modifies the input variable.
• The second property is also known as immutability.
• The only result of the Pure Function is the value it returns.
• They are deterministic.
• Pure functions also make it easier to write parallel/concurrent
applications.
Pure Functions (Cont..)
• A function is called pure function if it always returns the same result
for same argument values and it has no side effects like modifying an
argument (or global variable) or outputting something.
• The only result of calling a pure function is the return value.
• Examples of pure functions are strlen(), pow(), sqrt() etc.
• Examples of impure functions are printf(), rand(), time(), etc.
• If a function is known as pure to compiler then Loop
optimization and subexpression elimination can be applied to it.
• In GCC, the “pure” attribute is used to mark the function as pure
funciton.
Python program to demonstrate pure functions
# A pure function that does Not
# changes the input list and
# returns the new List
• def pure_func(List):
• New_List = []
• for i in List:
• New_List.append(i**2)
Program (Cont..)
return New_List
# Driver's code
• Original_List = [1, 2, 3, 4]
• Modified_List = pure_func(Original_List)

• print("Original List:", Original_List)


• print("Modified List:", Modified_List)

Output:
Original List: [1, 2, 3, 4]
Modified List: [1, 4, 9, 16]
Recursion
• During functional programming, there is no concept of for loop
or while loop, instead recursion is used.
• Recursion is a process in which a function calls itself directly or
indirectly.
• In the recursive program, the solution to the base case is provided
and the solution to the bigger problem is expressed in terms of
smaller problems.
• A question may arise what is base case? The base case can be
considered as a condition that tells the compiler or interpreter to exit
from the function.
Python program to demonstrate recursion
# Recursive Function to find
# sum of a list
• def Sum(L, i, n, count):
• # Base case
• if n <= i:
• return count
• count += L[i]
# Going into the recursion
• count = Sum(L, i + 1, n, count)
• return count
Program(Cont..)
# Driver's code
• L = [1, 2, 3, 4, 5]
• count = 0
• n = len(L)
• print(Sum(L, 0, n, count))

Output:
15
Built-in Higher-Order Functions - Functions are First-Class
and can be Higher-Order

• First-class objects are handled uniformly throughout.

• They may be stored in data structures, passed as arguments, or used


in control structures.

• A programming language is said to support first-class functions if it


treats functions as first-class objects.
Properties of first class functions
• A function is an instance of the Object type.
• To store the function in a variable.
• To pass the function as a parameter to another function.
• To return the function from a function.
• To store them in data structures such as hash tables, lists,. etc.
Python program to demonstrate higher order functions

• def shout(text):
• return text.upper()
• def whisper(text):
• return text.lower()
• def greet(func):
• # storing the function in a variable
• greeting = func("Hi, I am created by a function passed as an
argument.")
• print(greeting)
Program (Cont..)
• greet(shout)
• greet(whisper)

Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, I am created by a function passed as an argument.
Built-in Higher-order functions
• To make the processing of iterable objects like lists and iterator much easier,
Python has implemented some commonly used Higher-Order Functions.
• These functions return an iterator that is space-efficient. Some of the built-
in higher-order functions are:
Map(): map() function returns a list of the results after applying the given
function to each item of a given iterable (list, tuple etc.)
• Syntax: map(fun, iter)
Parameters:
• fun: It is a function to which map passes each element of given iterable.
• iter: It is a iterable which is to be mapped.
• Return Type: Returns an iterator of map class.
Python program to demonstrate working of map.

# Return double of n
• def addition(n):
• return n + n
# We double all numbers using map()
• numbers = (1, 2, 3, 4)
• results = map(addition, numbers)
# Does not Print the value
• print(results)
Program (Cont..)
# For Printing value
• for result in results:
• print(result, end = " ")

Output:
<map object at 0x7fae3004b630>
2468
Built-in Higher-order functions - Filter
• filter(): The filter() method filters the given sequence with the help of
a function that tests each element in the sequence to be true or not.
Syntax: filter(function, sequence)
Parameters:
• function: a function that tests if each element of a sequence true or
not.
• sequence: sequence which needs to be filtered, it can be sets, lists,
tuples, or containers of any iterators.
• Return Type: returns an iterator that is already filtered.
Python program to demonstrate working of
the filter.
# function that filters vowels
• def fun(variable):
• letters = ['a', 'e', 'i', 'o', 'u']

• if (variable in letters):
• return True
• else:
• return False
# sequence
• sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
Program (Cont..)
# using filter function
• filtered = filter(fun, sequence)
• print('The filtered letters are:')
• for s in filtered:
• print(s)

Output:
The filtered letters are:
e
e
Immutability
• Immutability is a functional programming paradigm can be used for
debugging as it will throw an error where the variable is being
changed not where the value is changed.
• Python too supports some immutable data types like string, tuple,
numeric, etc.

# Python program to demonstrate


# immutable data types
# String data types
• immutable = "GeeksforGeeks"
Program (Cont..)
# changing the values will
# raise an error
• immutable[1] = 'K'

Output:
Traceback (most recent call last):
File "/home/ee8bf8d8f560b97c7ec0ef080a077879.py", line 10, in
immutable[1] = 'K'
TypeError: 'str' object does not support item assignment
Anonymous Function With lambda
• Functional programming is all about calling functions and passing
them around, so it naturally involves defining a lot of functions.
• It can be defined, using the def keyword.
• It’s convenient to be able to define an anonymous function on the fly,
without having to give it a name.
• In Python, it is achied with a lambda expression.
Lambda Function Example
• lambda <parameter_list>: <expression>

• >>> lambda s: s[::-1]


• 2<function <lambda> at 0x7fef8b452e18>
• 3
• 4>>> callable(lambda s: s[::-1])
• 5True
Logic Programming paradigm
• Logic Programming is the combination of two words, logic and
programming.
• Logic Programming is a programming paradigm in which the problems
are expressed as facts and rules by program statements but within a
system of formal logic.
• Just like other programming paradigms like object oriented,
functional, declarative, and procedural, etc., it is also a particular way
to approach programming.
Logic Programming paradigm
(Cont..)
• Logic programming is a programming paradigm that sees computation
as automatic reasoning over a database of knowledge made of facts
and rules.
• It is a way of programming and is based on formal logic.
• A program in such a language is a set of sentences, in logical form,
one that expresses facts and rules about a problem domain.
• Among others, Datalog is one such major logic programming language
family.
Solving Problems using Logic
Programming
• Logic Programming uses facts and rules for solving the problem.
• A goal needs to be specified for every program in logic programming.
• To understand how a problem can be solved in logic programming,
First to know about the building blocks − Facts and Rules.
Facts
• Actually, every logic program needs facts to work with so that it can
achieve the given goal.
• Facts basically are true statements about the program and data. For
example, Delhi is the capital of India.
Logic Programming (Cont..)
Rules
• Actually, rules are the constraints which allow us to make conclusions
about the problem domain.
• Rules basically written as logical clauses to express various facts.
• For example, if we are building any game then all the rules must be
defined.
• Rules are very important to solve any problem in Logic Programming.
Rules are basically logical conclusion which can express the facts.
Syntax for Rule
• Following is the syntax of rule −
A∶− B1,B2,...,Bn.
• Here, A is the head and B1, B2, ... Bn is the body.
For example − ancestor(X,Y) :- father(X,Y).
• ancestor(X,Z) :- father(X,Y), ancestor(Y,Z).
• This can be read as, for every X and Y, if X is the father of Y and Y is an
ancestor of Z, X is the ancestor of Z.
• For every X and Y, X is the ancestor of Z, if X is the father of Y and Y is
an ancestor of Z.
Packages for Logic Programming
Kanren
• It provides us a way to simplify the way we made code for business logic. It
lets us express the logic in terms of rules and facts.
The following command will help you install kanren −
• pip install kanren
SymPy
• SymPy is a Python library for symbolic mathematics.
• It aims to become a full-featured computer algebra system (CAS) while
keeping the code as simple as possible in order to be comprehensible and
easily extensible.
The following command will help you install SymPy.
• pip install sympy
Logic Programming - Checking for Prime Numbers
• from kanren import isvar, run, membero
• from kanren.core import success, fail, goaleval, condeseq, eq, var
• from sympy.ntheory.generate import prime, isprime
• import itertools as it
• def prime_check(x):
• if isvar(x):
• return condeseq([(eq,x,p)] for p in map(prime, it.count(1)))
• else:
• return success if isprime(x) else fail
Checking for Prime Numbers( Cont..)
• x = var()
• print((set(run(0,x,(membero,x,
(12,14,15,19,20,21,22,23,29,30,41,44,52,62,65,85)),
• (prime_check,x)))))
• print((run(10,x,prime_check(x))))

The output of the above code will be as follows −


{19, 23, 29, 41}
(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)

You might also like