0% found this document useful (0 votes)
3 views28 pages

Python Unit3

This document provides notes on Unit III of a Python programming course, focusing on functions and strings. It covers the definition, types, and usage of functions, including built-in and user-defined functions, as well as concepts like function composition, recursion, and scope. Additionally, it explains string manipulation techniques and the importance of modular programming in Python.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
3 views28 pages

Python Unit3

This document provides notes on Unit III of a Python programming course, focusing on functions and strings. It covers the definition, types, and usage of functions, including built-in and user-defined functions, as well as concepts like function composition, recursion, and scope. Additionally, it explains string manipulation techniques and the importance of modular programming in Python.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 28

EASWARI ENGINEERING COLLEGE

(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE

191GES102T – PROBLEM SOLVING THROUGH PYTHON


PROGRAMMING

Unit III -Notes

I YEAR –B.E/B.TECH
(Common to all Branches)

PREPARED BY APPROVED BY

J.PRIYA HOD
UNIT III
FUNCTIONS AND STRINGS
Modules and functions: function definition and use, flow of execution, parameters and
arguments; Fruitful functions: return values, composition, recursion; Strings: string slices,
immutability, Looping and counting, String methods.

Modules:
Python module can be defined as a python program file which contains a python code including
python functions, class, or variables. The python code file saved with the extension (.py) is
treated as the module. a runnable code is present inside the python module. A module in
Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.

Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)

Note:
In python help () is there. The name of any module, keyword, or topic can be entered to get
help on writing Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type
"quit".
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys.version)
3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:37:30) [MSC v.1927 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=6, releaselevel='final', serial=0)

>>> import calendar


>>> print(calendar.month(2021,5))

>>>print(calendar.isleap(2020))
True
>>> print(calendar.isleap(2017))
False

Functions
➢ A function is a group of related statements that performs a specific task.
➢ Functions help break our program into smaller and modular chunks. As our program grows larger
and larger, functions make it more organized and manageable.
➢ Furthermore, it avoids repetition and makes the code reusable.
➢ Python enables its programmers to break up a program into segments commonly known as
functions, each of which can be written more or less independently of the others. Every function in
the program is supposed to perform a well-defined task.

Need for Functions


➢ Understanding, coding and testing multiple separate functions is far easier.
➢ Without the use of any function, then there will be countless lines in the code and maintaining it
will be a big mess.
➢ Programmers use functions without worrying about their code details. This speeds up program
development, by allowing the programmer to concentrate only on the code that he has to write.
➢ Different programmers working on that project can divide the workload by writing different
functions.
➢ Like Python libraries, programmers can also make their functions and use them from different
point in the main program or any other program that needs its functionalities.

Function Declaration and Definition


➢ A function, f that uses another function g, is known as the calling function and g is known as the
called function.
➢ The inputs that the function takes are known as arguments/parameters.
➢ The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters, else not.
➢ Function declaration is a declaration statement that identifies a function with its name, a list of
arguments that it accepts and the type of data it returns.
➢ Function definition consists of a function header that identifies the function, followed by the body
of the function containing the executable code for that function.
Functions and its use:
Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))

Output:
Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.


def add_numbers(x,y):
sum = x + y
return sum
print("The sum is", add_numbers(5, 20))

Output:
The sum is 25

Resolution of Names
• Scope defines the visibility of a name within a block. If a local variable is defined in a
block, its scope is that particular block. If it is defined in a function, then its scope is all
blocks within that function.
• When a variable name is used in a code block, it is resolved using the nearest enclosing
scope. If no variable of that name is found, then a NameError is raised. In the code given
below, str is a global string because it has been defined before calling the function.
• Example:
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statement
there, and then comes back to pick up where it left off.

Example:
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning ")
Output:
welcome
0
1
2
Good morning

Fruitful Function
❖ Fruitful function
❖ Void function
❖ Return values
❖ Parameters
❖ Local and global scope
❖ Function composition
❖ Recursion
Example:

Example:
#Example for fruitful function
def add(x,y):
sum=x+y
return sum
a=int(input("Enter a ="))
b=int(input("Enter b ="))
print("Addition of two numbers=",add(a,b))

Output:
Enter a=5
Enter b=5

Addition of two numbers= 10

Void Function
A function that perform action but don‟t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values:

The return statement is used to return values from the function definition to the to the
function call statement. Return takes zero, values or an expression. Default value is none.
Syntax:
return

Example :
#Example to show return statement in a function

def square(n):
returnn*n
print("The square is ",square(5))

Output:
The square is25
Write a Python function that takes two lists and returns True if they have at least one
common member.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:
True
True
None
Functions with multiple return statements:

A function can have multiple return statements, one in each branch of a conditional. Since
these return statements are in an alternative conditional, only one runs. As soon as a
return statement runs, the function terminates without executing any subsequent
statements. Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.
Example:
#Example to show multiple return statements

def absolute(x):
if x<0:
print("This is if")
return-x
elif x>0: return
x
print("This is another elif") #dead code
else:
print("This is else") return
0
a=int(input("Enter the value"))
print(absolute(a))
Output:
First execution:
Enter the value -5
This is if
5
Second execution:
Enter the value 5
5
Third execution:
Enter the value 0
This is else
0

Parameters in Fruitful Functions


Function:
Definition:

A function is a group of related statements that perform a specific task. A function is a


named sequence of statements that performs a computation. Function is defined as a sub
program which contains a set of instructions to perform a specific task.
Parameters/Arguments:
A function in python
• Takes input data, called parameters or arguments
• Performs some computations
• Return the result
Syntax:
def function_name(param1,param2);
Statements return
result
Function call:
Once a function is defined, it must be called
Syntax:
result=function_name(param1,param2)
Parameters:
Parameter is the input data that is sent from one function to another. The parameters are
of two types:
Formal parameters:
This parameter defined as part of the function definition.
The actual parameter value is received by the formal parameter

Actual parameters:
This parameter defined in the function call
Example:
#Example for actual and formal parameters
def cube(x):
return x*x*x
a=int(input("Enter the number="))
b=cube(a)
print("Cube of the given number=",b)

Example:
Enter the number=5
Cube of the given number= 125
Actual arguments, or simply ―arguments, are the values passed to functions to be
operated on. Formal parameters, or simply ―parameters, are the placeholder names for
the arguments passed.
#Type1 : No parameters and no return type
def Fun1() :
print("function 1")
Fun1()
Output:
function 1

#Type 2: with parameter without return type


def fun2(a) :
print(a)
fun2("hello")
Output:
Hello

#Type 3: without parameter with return type


def fun3():
return "welcome to python"
print(fun3())
Output:
welcome to python
#Type 4: with parameter with return type
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
python is better then c
Types of parameters:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number
of arguments in the function call.
Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the parameter
according to their position. When we call functions in keyword parameter, the order of the
arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")

Default parameter:
Python allows function parameter to have default values; if the function is called without the
argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
student( “kumar”): Ajay 17
student( “ajay”):
Variable length parameter

❖ Sometimes, we do not know in advance the number of arguments that will be


passed into a function.
❖ Python allows us to handle this kind of situation through function calls with
number of arguments.
❖ In the function definition we use an asterisk (*) before the parameter name to
denote this is variable length of parameter.
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name, mark)
student (“bala”,102,90)
Parameter passing techniques:
There are two parameter passing techniques in programming languages
1. call by value:
In call by value, a copy of actual arguments is passed to formal arguments and any
changes made to the formal arguments have no effect on the actual arguments
2. call by reference:
In call by reference, the address of actual arguments is passed to formal arguments. By
accessing the addresses of formal arguments, any changes made in formal arguments
will be reflected in actual arguments.
In python there is no call by reference or value, it uses a mechanism known as call by
object
void functions:
The functions without return statement are known as void functions. In these functions
the return value is none
#Example for void functions
def simple():
print("Hello")
print("This is an example for void functions")
simple()
Output:
Hello
This is an example for void functions

Local and Global Scope

Global Scope
❖ The scope of a variable refers to the places that you can see or access a variable.
❖ A variable with global scope can be used anywhere in the program.
❖ It can be created by defining a variable outside the function.

A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file. The variable
defined inside a function can also be made global by using the global statement.
def function_name(args):
.............
Example output
a=50
def add(): Global Variable

b=20 70
c=a+b
print(c)
def sub():
b=30
Local Variable
20
c=a-b
50
print(c)
print(a)

global x #declaring global variable inside a function


............
Local Scope
A variable with local scope can be used only within the function.
create a local variable
def f1():
y = "local"
print(y)
f1()
Output:
local

If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,

# use local and global variables in same code


x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
globalglobal
local

# use Global variable and Local variable with same name


x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)

Output:
local x: 10
global x: 5

Example output
def add():
b=20
c=a+b 70
print(c) Local Variable

def sub():
20
b=30
c=a-b Local Variable
print(c)
error
print(a)
error
print(b)

Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.

Example 1:
#create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5) # FunctionC(x)
12

Example: Output:
math.sqrt(math.log(10))
def 900
add(a,b):
c=a+b
return c
def
mul(c,d)
: e=c*d
return e
c=add(10,20
)
e=mul(c,30)
print(e)

❖ Function Composition is the ability to call one function from within another
function
❖ It is a way of combining functions such that the result of each function is passed as the
argument of the next function.
In other words the output of one function is given as the input of another function
is known as function composition.

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=int(input("enter a:"))
b=int(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

#Example for function


composition a=int(input("Enter 1st
number")) b=int(input("Enter 2nd
number")) c=a+b
print("The addition of two numbers is:",c)

Output:
Enter 1st number5
Enter 2nd number5
The addition of two numbers is: 10
In this example the statement , int(input("Enter 1st number"))
Uses a technique known as function composition. It combines the input and int functions
into one statement. The result of the input function is passed directly to int function

Example2:
#Example for function composition
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2 +((y2-y1)**2))

def area2(xc, yc, xp, yp):


return area(distance(xc,yc,xp,yp)) #Function composition

def area(radius):
return 3.14*radius*radius

print("The area of circle is:",area2(1,2,4,6)) #Function call

Output:
The area of circle is: 78.5

In this example, a function is written that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle. Assume that the center point
is stored in the variables xc and yc, and the perimeter point is in xp and yp.

The first step is to find the radius of the circle, which is the distance between the two
points.
radius = distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that
radius: result = area(radius)
Encapsulating these steps in a function, we get:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

Recursion
A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion

Factorial of n Output
def fact(n): enter no. to find fact:5 Fact
if(n==1): is 120
return 1 else:
return n*fact(n-1)

n=int(input("enter no. to find fact:"))


fact=fact(n)
print("Fact is",fact)
Explanation

Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion

Sum of n numbers Output


def sum1(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum1(n-1)

n=int(input("enter no. to find sum:"))


sum1=sum1(n)
print("Fact is",sum)

Strings:
❖ Strings
❖ String slices
❖ Immutability
❖ String functions and methods
❖ String module
Strings:
❖ String is defined as sequence of characters represented in quotation marks (either
single quotes ( „ ) or double quotes ( “).
❖ An individual character in a string is accessed using a index.
❖ The index should always be an integer (positive or negative).
❖ A index starts from 0 ton-1.
❖ Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
❖ Python will get the input at run time by default as a string.
❖ Python does not supportcharacterdatatype.Astringofsize1canbetreatedas
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations onstring:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership

>>>a=”HELLO” ❖ Positive indexing helps in accessing the


indexing >>>print(a[0]) string from the beginning
>>>H ❖ Negative subscript helps in accessing the
>>>print(a[-1]) string from the end.

>>>O

Print[0:4] –HELL The Slice[start : stop] operator extracts sub


Slicing: Print[ :3] – HEL string from the strings.
Print[0: ]-HELLO A segment of a string is called a slice.
a= “save” The + operator joins the text on both sides
Concatenation b=“earth” of the operator.
>>>print(a+b)
saveearth

a= “Easwari ” The * operator repeats the string on the left


Repetitions: >>>print(3*a) hand side times the value on right hand side.
Easwari Easwari
Easwari

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present
>>> "a" not in s
True
String slices:
❖ A part of a string is called string slices.
❖ The process of extracting a sub string from a string is called slicing.

String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.

Default value of start is 0,


- Stop is last index of list
- And for step default is 1

For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Print[0:4] –HELL The Slice[n : m] operator extracts sub string
Slicing: Print[ :3] – HEL from the strings.
a=”HELLO” Print[0: ]-HELLO A segment of a string is called a slice.

Immutability:
❖ Python strings are “immutable” as they cannot be changed after they are created.
❖ Therefore [ ] operator cannot be used on the left side of an assignment.

For example:
>>> greeting= ‘Eswari college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the
original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator

operations Example output


element assignment a="PYTHON" TypeError: 'str' object does not
a[0]='x' support element assignment

element deletion a=”PYTHON” TypeError: 'str' object doesn't


del a[0] support element deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined
print(a)
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method


Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>>a.capitalize() capitalize only the first
' Happybirthday‟ letter in a string
2 a.upper() >>> a.upper() change string to upper
'HAPPY BIRTHDAY‟ case
3 a.lower() >>> a.lower() change string to lower
' happy birthday‟ case
4 a.title() >>> a.title() change string to title case
' Happy Birthday ' i.e. first characters of all
the words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase
'HAPPY BIRTHDAY' characters to uppercase
and viceversa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar”) >>>a.center(19,”*”) pads the string with the
'***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring

9 a.replace(old,new) >>>a.replace('happy', replace all old substrings


'wishyou happy') with new substrings
'wishyou happy birthday'
10 a.join(b) >>> b="happy" returns a string
>>>a="-" concatenated with the
>>>a.join(b) elements of an iterable.
'h-a-p-p-y' (Here “a” is the iterable)
11 a.isupper() >>> a.isupper() checks whether all the
False case-based characters
(letters) of the string are
uppercase.
12 a.islower() >>> a.islower() checks whether all the
True case-based characters
(letters) of the string are
lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace
only.
17 a.istitle() >>> a.istitle() checks whether string is
False title cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether string
True starts with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring,
0 if it is found. Otherwise -1
is returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>‟ „ character in the string
23 max(a) max(a) Return the maximum
>>>‟y‟ character in the string
String modules:
❖ A module is a file containing Python definitions, functions, statements.
❖ Standard library of Python is extended as modules.
❖ To use these modules in a program, programmer needs to import the module.

❖ Once we import a module, we can reference or use to any of its functions or variables
in ourcode.
❖ There is large number of standard modules also available in python.
❖ Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes
Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)

Python String Module Classes


Python string module contains two classes – Formatter and Template.
Formatter
It behaves exactly same as str.format() function. This class becomes useful if you want to
subclass it and define your own format string syntax.
Syntax: from string import Formatter
Template
This class is used to create a string template for simpler string substitutions
Syntax: from string import Template

Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK
print(string.capwords("happy LMNOPQRSTUVWXYZ!"#$%&'()*+,-
birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote (") >>>print("\"")
"
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

ILLUSTRATIVE PROGRAMS:
1. SQUARE ROOT
#Python program to find the square root of a number using newton's method using
user defined function
n= float(input("Enter a number to find the squareroot: "))
def nsquare_root(n):
estimate = n/2
newestimate = (estimate+(n/estimate))/2
estimate = newestimate
newestimate = (estimate+(n/estimate))/2
return(newestimate)
newestimate=nsquare_root(n)
print("The square root of the number using newton method is:",newestimate)
OUTPUT:
Enter a number to find the squareroot: 2
The square root of the number using newton method is: 1.414213562373095

2. GCD
Program to find GCD/HCF of two numbers using
Recursion #Program to find the gcd/hcf using recursion
def gcd(a,b):
if(a==0): return
b
if(b==0): return
a
return gcd(b,a%b) a=int(input("Enter
first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)

OUTPUT:
Enter first number:8
Enter second number:12
GCD is:
4

3. EXPONENTIATION

Program to find Power/Exponentiation of a number using Recursion


#Exponentiation or power of a number using recursion
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponent: "))
print("The power of a number is",power(base,exp))
OUTPUT:
Enter base: 5
Enter exponent: 2
The power of a number is 25

4. SUM AN ARRAY OFNUMBERS


Program to Sum an array of numbers using iteration Sum an array
of numbers(Using Lists)

Program:

l=[1,2,3,4,5]
s=0
for i in l:
s=s+i
print("The sum of numbers of an array using list is",s)
Output:
The sum of numbers of an array using list is 15
Sum an array of numbers(Using arrays)
Program:
from array import *
my_array=array('i',[1,2,3,4,5])
s=0
for i in my_array:
s=s+i
print("The sum of numbers of an array is",s)
Output:

The sum of numbers of an array is 15


5. LINEARSEARCH
Program to search a number using Linear search
Given a list of n elements, write a function to search a given element x in
the list. A simple approach is to do linear search, i.e
• Start from the leftmost element of the list and one by one compare x with
each element of list
• If x matches with an element, print the element is present in the list.
• If x does not match with any of elements, print the element is not present in the list
The time complexity of above algorithm isO(n).
#Program for linear search
def linearsearch(list,search):
print("The elements in the list is",list)
n=len(list)
for i in range(0,n):
if(list[i]==search):
print("The element is present in the list at position",i+1) break
else:
print("The element is not present in the list") return
l=[20,100,60,120,140]
s=int(input("Enter the element to be searched in the list:"))
linearsearch(l,s)
OUTPUT:
Enter the element to be searched in the list:140 The
elements in the list is [20, 100, 60, 120, 140] The
element is present in the list at position 4
On second execution:
Enter the element to be searched in the list:160
The elements in the list is [20, 100, 60, 120, 140]
The element is not present in the list

6. BINARYSEARCH

Binary Search
Given a sorted list of n elements, write a function to search a given element x in
list. Search a sorted array by repeatedly dividing the search interval into half.
Begin with an interval covering the whole array. If the value of the search key is
less than the item in the middle of the interval, narrow the interval to the lower
half. Otherwise narrow it to the upper half. Repeatedly check until the value is
found or the interval is empty. The time complexity is to O(Log n).

Program to search a number using Binary search


PROGRAM:
#Program for Binary Search
def bsearch(list,search): first=0
last=len(list)-1
while first<=last:
mid=(first+last)//2
iflist[mid]==search:
print("element found in position",mid) break
else:
if search<list[mid]:
last=mid-1
else:
first=mid+1
else:
print("The element is not present in the list") return
a=[]
n=int(input("enter upper limit"))
for i in range(0,n):
e=int(input("enter the elements"))
a.append(e)
x=int(input("enter element to search"))
bsearch(a,x)

OUTPUT:
enter upper limit5
enter the elements20
enter the elements40
enter the elements60
enter the elements80
enter the elements100

enter element to search100


element found in position 4

On second execution:
enter upper limit5
enter the elements20
enter the elements40
enter the elements60
enter the elements80
enter the elements100
enter element to search120
The element is not present in the list

You might also like