Unit 4 APP
Unit 4 APP
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.
Functional Programming in Python
• Functional Programming is a popular programming paradigm closely linked to computer science's mathematical foundations.
While there is no strict definition of what constitutes a functional language, we consider them to be languages that use
functions to transform data.
• Python is not a functional programming language but it does incorporate some of its concepts alongside other programming
paradigms. With Python, it's easy to write code in a functional style, which may provide the best solution for the task at hand.
Pure Functions in Python
• If a function uses an object from a higher scope or random numbers, communicates with files and so on, it might be impure
Built-in Higher Order Functions
Map
• The map function allows us to apply a function to every element in an iterable object
Filter
• The filter function tests every element in an iterable object with a function that returns either True or False, only keeping those
which evaluates to True.
Combining map and filter
• As each function returns an iterator, and they both accept iterable objects, we can use them together for some really
expressive data manipulations!
List Comprehensions
• A popular Python feature that appears prominently in Functional Programming Languages is list comprehensions. Like the map
and filter functions, list comprehensions allow us to modify data in a concise, expressive way.
Anonymous Function
• In Python, anonymous function is a function that is defined without a name.
• While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda
keyword.
Characteristics of Python lambda functions:
• A lambda function can take any number of arguments, but they contain only a single expression. An expression is a piece of code
executed by the lambda function, which may or may not return any value.
• Lambda functions can be used to return function objects.
• Syntactically, lambda functions are restricted to only a single expression.
Syntax of Lambda Function in python
lambda arguments: expression
Example:
double = lambda x: x * 2 product = lambda x, y : x * y
print(double(5)) print(product(2, 3))
# Output: 10
Note: you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their
map() Function
Example Map with lambda Example with Map
tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61) from math import sqrt
list_a = [1, 2, 3] #splitting the input and convert to int using map
Syntax:
map(function, iterables)
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