PROGRAMMING PARADIGMS
PROGRAMMING PARADIGMS
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
• 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.
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>
def print_cube(num):
print("Cube: {}".format(num * num * num))
def print_square(num):
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating processes
p1 = multiprocessing.Process(target=print_square, args=(10, ))
p2 = multiprocessing.Process(target=print_cube, args=(10, ))
# starting process 1
p1.start()
# starting process 2
p2.start()
O/P
Square: 100 Cube: 1000 Done!
•To import the multiprocessing module, we do:
import multiprocessing
•To create a process, we create an object of Process class. It takes following
arguments:
•target: the function to be executed by process
•args: the arguments to be passed to the target function
def worker1():
# printing process id
print("ID of process running worker1: {}".format(os.getpid()))
def worker2():
# printing process id
print("ID of process running worker2: {}".format(os.getpid()))
if __name__ == "__main__":
# printing main program process id
print("ID of main process: {}".format(os.getpid()))
# creating processes
p1 = multiprocessing.Process(target=worker1)
p2 = multiprocessing.Process(target=worker2)
# starting processes
p1.start()
p2.start()
# process IDs
print("ID of process p1: {}".format(p1.pid))
print("ID of process p2: {}".format(p2.pid))
In the context of the Internet, clients are typically run on desktop or laptop computers attached to the Internet looking for
information, whereas servers are typically run on larger computers with certain types of information available for the clients to
retrieve. The Web itself is made up of a bunch of computers that act as Web servers; they have vast amounts of HTML pages and
related data available for people to retrieve and browse. Web clients are used by those of us who connect to the Web servers and
browse through the Web pages.
Network programming uses a particular type of network communication known as sockets. A socket is a software abstraction for an
input or output medium of communication.
What is Socket?
• A socket is a software abstraction for an input or output medium of communication.
• Sockets allow communication between processes that lie on the same machine, or on different machines working in diverse
environment and even across different continents.
• A socket is the most vital and fundamental entity. Sockets are the end-point of a two-way communication link.
• An endpoint is a combination of IP address and the port number.
For Client-Server communication,
▪ Sockets are to be configured at the two ends to initiate a connection,
▪ Listen for incoming messages
▪ Send the responses at both ends
▪ Establishing a bidirectional communication.
Socket Types
Datagram Socket
• A datagram is an independent, self-contained piece of information sent over a network whose arrival, arrival time, and content
are not guaranteed. A datagram socket uses User Datagram Protocol (UDP) to facilitate the sending of datagrams (self-contained
pieces of information) in an unreliable manner. Unreliable means that information sent via datagrams isn't guaranteed to make it
to its destination.
Stream Socket:
• A stream socket, or connected socket, is a socket through which data can be transmitted continuously. A stream socket is more
akin to a live network, in which the communication link is continuously active. A stream socket is a "connected" socket through
which data is transferred continuously.
Socket in Python
listen(backlog) : This method listens for the connection made to the socket. The backlog is the maximum number of queued
connections that must be listened before rejecting the connection.
accept( ) : This method is used to accept a connection. The socket must be bound to an address and listening for connections. The
return value is a pair(conn, address) where conn is a new socket object which can be used to send and receive data on that
connection, and address is the address bound to the socket on the other end of the connection.
General Socket in Python
sock_object.recv():
Use this method to receive messages at endpoints when the value of the protocol parameter is TCP.
sock_object.send():
Apply this method to send messages from endpoints in case the protocol is TCP.
sock_object.recvfrom():
Call this method to receive messages at endpoints if the protocol used is UDP.
sock_object.sendto():
Invoke this method to send messages from endpoints if the protocol parameter is UDP.
sock_object.gethostname():
This method returns hostname.
sock_object.close():
This method is used to close the socket. The remote endpoint will not receive data from this side.
Simple TCP Server
Simple TCP Client
Simple UDP Server
Simple UDP Client
import socket
s.bind((HOST, PORT))
s.listen()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
import socket
HOST = "127.0.0.1"
PORT = 65432
s.connect((HOST, PORT))
data = s.recv(1024)
print(f"Received {data!r}")
An IP address is the address of a computer on a network.
A port is a number between 1 and 65535.
A socket is one half a channel of communication between two computers over a network on a particular port. (the other half is the corresponding socket on the other
computer)