0% found this document useful (0 votes)
65 views139 pages

LAB 4 Sem

The document is a laboratory manual for the Design and Analysis of Algorithms course (22CSL46) at a women's engineering college. It includes various programming assignments that cover algorithms such as binary search, quick sort, merge sort, dynamic programming for the 0/1 knapsack problem, Dijkstra's algorithm, and minimum cost spanning trees using Kruskal's and Prim's algorithms. Each section provides coding examples and expected outputs for the algorithms implemented.

Uploaded by

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

LAB 4 Sem

The document is a laboratory manual for the Design and Analysis of Algorithms course (22CSL46) at a women's engineering college. It includes various programming assignments that cover algorithms such as binary search, quick sort, merge sort, dynamic programming for the 0/1 knapsack problem, Dijkstra's algorithm, and minimum cost spanning trees using Kruskal's and Prim's algorithms. Each section provides coding examples and expected outputs for the algorithms implemented.

Uploaded by

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

DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

Faculty of Engineering & Technology (Exclusively


for Women)

ALGORITHMS Laboratory
(22CSL46)
Manual

Department of Computer Science and


Engineering

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 1


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

INDEX
PART-A

1. Design a program to search a key element of n integers using binary


search algorithm and compute time complexity
2. Design a program to Sort a given set of n integer elements using
Quick Sort method and compute its time complexity.
3. Design a program to sort set of n integer elements using Merge Sort
method and compute its time complexity.
4. Implement the 0/1 Knapsack problem using Dynamic Programming
method. Greedy method.
5. Design a program to print all the node reachable from a given starting
node in a given digraph using DFS method.

PART – B

6. Write a Program find shortest paths to other vertices using Dijkstra's


algorithm.
7. ( a ) Write a program to find a Minimum Cost Spanning Tree of a
given connected undirected graph using Kruskal's algorithm.
( b ) Write a program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Prim’s algorithm.
8. Write a program to
( a ) Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
( b ) Implement transitive closure using warshall Algorithm.
9. Design and implement to find a subset of a given set.
10. Implement Travelling Salesman problem using Dynamic program

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 2


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

1. Design a program to search a key element of n integers using binary search algorithm and compute
time complexity.

int binarySearch(int arr[], int l, int r, int x)


{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ;
printf("Element is not present in array")
printf("Element is present at index %d", result);
return 0;
}
OUTPUT:

Element is present at index 3

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 3


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

2.Design a program to Sort a given set of n integer elements using Quick Sort method and compute
its time complexity.

# include <stdio.h>
# include <time.h>
void Exch(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
void QuickSort(int a[], int low, int high)
{
int i, j, key, k;
if(low>=high)
return;
key=low; i=low+1; j=high;
while(i<=j)
{
while ( a[i] <= a[key] ) i=i+1;
while ( a[j] > a[key] ) j=j-1;
if(i<j) Exch(&a[i], &a[j]);
}
Exch(&a[j], &a[key]);
QuickSort(a, low, j-1);
QuickSort(a, j+1, high);
}
void main()
{
int n, a[1000],k,clock_tst,et,st,clocks_per_sec;
clock_t st,et;
double ts;
printf("\n Enter How many Numbers: ");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t",a[k]);
}
st=clock();

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 4


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

QuickSort(a, 1, n);
et=clock();
ts=(double)(et-st)/CLOCKS_PER_SEC;
printf("\nSorted Numbers are: \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
}
OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 5


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

3. Design a program to sort set of n integer elements using Merge Sort method and compute its time
complexity.

# include <stdio.h>
#include<time.h>
void Merge(int a[], int low, int mid, int high)
{
int i, j, k, b[20];
i=low; j=mid+1; k=low;
while ( i<=mid && j<=high )
{
if( a[i] <= a[j] )
b[k++] = a[i++] ;
else
b[k++] = a[j++] ;
}
while (i<=mid) b[k++] = a[i++] ;
while (j<=high) b[k++] = a[j++] ;
for(k=low; k<=high; k++)
a[k] = b[k];
}
void MergeSort(int a[], int low, int high)
{
int mid;
if(low >= high)
return;
mid = (low+high)/2 ;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
}
void main()
{
int n, a[2000],k;
clock_t st,et;
double ts;
printf("\n Enter How many Numbers:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 6


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
MergeSort(a, 1, n);
et=clock();
ts=(double)(et-st)/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
}

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 7


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

4. Implement the 0/1 Knapsack problem using

(a) Dynamic Programming method.


(b) Greedy method.

A.
#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
void main()
{
int profit,count=0;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 8


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
}
OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 9


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

B.

# include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0;
int i, j, u;
u = capacity;

for (i = 0; i < n; i++)


x[i] = 0.0;

for (i = 0; i < n; i++) {


if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}

int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);
printf("\nEnter the wts and profits of each object:- ");
for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}
printf("\nEnter the capacityacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++) {
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++) {
for (j = i + 1; j < num; j++) {

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 10


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

if (ratio[i] < ratio[j]) {


temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}

knapsack(num, weight, profit, capacity);


return(0);
}
OUTPUT:
Enter the no. of objects:- 7

Enter the wts and profits of each object:-


2 10
35
5 15
77
16
4 18
13

Enter the capacity of knapsack:- 15

The result vector is:- 1.000000 1.000000 1.000000 1.000000


1.000000 0.666667 0.000000

Maximum profit is:- 55.333332

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 11


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

5. Design a program to print all the node reachable from a given starting node in a given digraph
using DFS method

#include<stdio.h>
#define infinity 999
void dij(int n,int v,int cost[10][10],int dist[100])
{
int i,u,count,w,flag[10],min;
for(i=1;i<=n;i++)
flag[i]=0,dist[i]=cost[v][i];
count=2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
min=dist[w],u=w;
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
void main()
{
int n,v,i,j,cost[10][10],dist[10];
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
}
printf("\n Enter the source vertex:");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n Shortest path:\n");

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 12


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}
OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 13


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

PART – B

1.Write a Program find shortest paths to other vertices using Dijkstra's algorithm.

#include<stdio.h>
#define infinity 999
void dij(int n,int v,int cost[10][10],int dist[100])
{
int i,u,count,w,flag[10],min;
for(i=1;i<=n;i++)
flag[i]=0,dist[i]=cost[v][i];
count=2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
min=dist[w],u=w;
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
void main()
{
int n,v,i,j,cost[10][10],dist[10];
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
}
printf("\n Enter the source vertex:");
scanf("%d",&v);
dij(n,v,cost,dist);

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 14


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

printf("\n Shortest path:\n");


for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}
OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 15


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

2.A.Write a program to find a Minimum Cost Spanning Tree of a given connected undirected
graph using Kruskal's algorithm.
2.B.Write a program to find Minimum Cost Spanning Tree of a given connected undirected
graph using Prim's algorithm.

A.
#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
printf("\n\n\tImplementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 16


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 17


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 18


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

B.
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 19


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 20


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

3.Write a program to
A.Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
B.Implement transitive closure using warshall Algorithm.

A.
#include<stdio.h>
int min(int,int);
void floyds(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 21


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 22


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 23


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

B.# include <stdio.h>


int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1) p[i][j]=1;
}
void main()
{
int i,j;
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is showm below\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 24


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 25


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

4.Design and implement to find a subset of a given set.

#include<stdio.h>
int s[10] , x[10],d ;
void sumofsub ( int , int , int ) ;
void main ()
{
int n , sum = 0 ;
int i ;
printf ( " \n Enter the size of the set : " ) ;
scanf ( "%d" , &n ) ;
printf ( " \n Enter the set in increasing order:\n" ) ;
for ( i = 1 ; i <= n ; i++ )
scanf ("%d", &s[i] ) ;
printf ( " \n Enter the value of d : \n " ) ;
scanf ( "%d" , &d ) ;
for ( i = 1 ; i <= n ; i++ )
sum = sum + s[i] ;
if ( sum < d || s[1] > d )
printf ( " \n No subset possible : " ) ;
else
sumofsub ( 0 , 1 , sum ) ;
}
void sumofsub ( int m , int k , int r )
{
int i=1 ;
x[k] = 1 ;
if ( ( m + s[k] ) == d )
{
printf("Subset:");
for ( i = 1 ; i <= k ; i++ )
if ( x[i] == 1 )
printf ( "\t%d" , s[i] ) ;
printf ( "\n" ) ;
}
else
if ( m + s[k] + s[k+1] <= d )
sumofsub ( m + s[k] , k + 1 , r - s[k] ) ;
if ( ( m + r - s[k] >= d ) && ( m + s[k+1] <=d ) )
{
x[k] = 0;

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 26


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

sumofsub ( m , k + 1 , r - s[k] ) ;
}
}
OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 27


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

5 .Implement Travelling Salesman problem using Dynamic program

#include<stdio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()
{
int i,j;

printf("Enter the number of cities: ");


scanf("%d",&n);

printf("\nEnter the Cost Matrix\n");

for(i=0;i < n;i++)


{
printf("\nEnter Elements of Row: %d\n",i+1);

for( j=0;j < n;j++)


scanf("%d",&ary[i][j]);

completed[i]=0;
}

printf("\n\nThe cost list is:");

for( i=0;i < n;i++)


{
printf("\n");

for(j=0;j < n;j++)


printf("\t%d",ary[i][j]);
}
}

void mincost(int city)


{
int i,ncity;

completed[city]=1;

printf("%d--->",city+1);
ncity=least(city);

if(ncity==999)

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 28


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];

return;
}

mincost(ncity);
}

int least(int c)
{
int i,nc=999;
int min=999,kmin;

for(i=0;i < n;i++)


{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}

if(min!=999)
cost+=kmin;

return nc;
}

int main()
{
takeInput();

printf("\n\nThe Path is:\n");


mincost(0); //passing 0 because starting vertex

printf("\n\nMinimum cost is %d\n ",cost);

return 0;
}

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 29


DESIGN AND ANALYSIS OF ALGORITHM LAB (22CSL46)

OUTPUT:

Dept.of CSE Faculty of Engineering &Technology(Exclusively for Women),KLB Page 30


1.Write a JavaScript to design a simple calculator to perform the
following operations: sum, product, difference and quotient.
<!DOCTYPE html>
<html>
<head>
<title>calculator-javascript and HTML</title>
<link rel="stylesheet" href="1a.css"></head>
<body>
<div id='calc-contain'>
<form name="calculator">
<input type="text"name="answer"/>
</br>
<input type="button" value="1"
onclick="calculator.answer.value+='1'"/>
<input type="button" value="2"
onclick="calculator.answer.value+='2'"/>
<input type="button" value="3"
onclick="calculator.answer.value+='3'"/>
<input type="button" value="+"
onclick="calculator.answer.value+='+'"/>
</br>
<input type="button" value="4"
onclick="calculator.answer.value+='4'"/>
<input type="button" value="5"
onclick="calculator.answer.value+='5'"/>
<input type="button" value="6"
onclick="calculator.answer.value+='6'"/>
<input type="button" value="-" onclick="calculator.answer.value+='-
'"/>
</br>
<input type="button" value="7"
onclick="calculator.answer.value+='7'"/>
<input type="button" value="8"
onclick="calculator.answer.value+='8'"/>
<input type="button" value="9"
onclick="calculator.answer.value+='9'"/>
<input type="button" value="*"
onclick="calculator.answer.value+='*'"/>
</br>
<input type="button" value="c" onclick="calculator.answer.value+='
'"/>
<input type="button" value="0"
onclick="calculator.answer.value+='0"'/>
<input type="button" value="="
onclick="calculator.answer.value=eval(calculator.answer.value)"/>
<input type="button" value="/" onclick="calculator.answer.value+='/'"/>
</br>
</form>
<div id="agn">
<p> GODUTAI ENGINEERING COLLEGE FOR WOMEN KLB</p>
</div>
</div>
</body>
</html>
1a.css
#calc-contain{
position:relative;
width:400px;
border:2px solid black;
border-radius:12px;
margin:0px auto;
padding:20px 20px 100px 20px;
}
#agh{
position:relative;
float:right;
margin-top:15px;
}
#agh p{
font-size:20px;
font-weight:900;
}
input[type=button]{
background;
lightGray; width:20%;
font-size:20px;
font-wight:900;
border-radius:7px;
margin-left:13px;
margin-top:10px;
}
input[type=button]:active{
background-color:#3e8e41;
box-shadow:0 5px #666;
transform:traslate Y (4px);
}
input[type=button]:hover{
background-color:#003300;
color:white;
}
input[type=text] {
position:relative;
display:block;
width:90%;
margin:5px auto;
font-size:20px;
padding:10px;
box-shadow:4px 0px 12px black inset;
}

2. Write a JavaScript that calculates the squares and cubes of the


numbers from 0 to 10 and outputs HTML text that displays the
resulting values in an HTML table format.

<html>
<head>
<script>
document.write ('<h1 align="right">Squares and Cubehsof the numbers
from 0 to 10</h1>');
document.write ('<center><table width="30%" border="1"
bgcolor="white">');
document.write
("<tr><th>Number</th><th>Square</th><th>cube</th><tr>");
for (var n=0; n<=10; n++)
{
document.write("<tr><td>"+n+"</td><td>"+n*n+"</td><td>"+n*n*n+"
</td></tr>");
}
document.write("</table>");
</script>
</head>
</html>
3.Write JavaScript to validate the following fields of the
Registration page.
a. First Name (Name should contains alphabets and the length
should not be less than 6 characters).
b. Password (Password should not be less than 6 characters
length).
c. E-mail id (should not contain any invalid and must follow the
standard pattern name@domain.com)
d. Mobile Number (Phone number should contain 10 digits
only).
e.Last Name and Address (should not be Empty).

Valid.js
function fun()
{
var userv=document.forms[0].user.value;
var pwdv=document.forms[0].pwd.value;
var emailv=document.forms[0].email.value;

var phv=document.forms[0].ph.value;
var userreg=new RegExp("^[a-zA-Z][a-zA-Z0-9]*$");
var emailreg=new RegExp("^[a-zA-Z][a-zA-Z0-9_.]*@[a-zA-
Z][a-zA-Z0-9_.]*.[a-zA-Z][a-zA-Z0-9_.]{2}.[a-zA-Z][a-zA-Z0-
9_.]{2}$|^[a-zA-Z][a-zA-Z0-9_.]*@[a-zA-Z][a-zA-Z0-9_.]*.[a-zA-
Z][a-zA-Z0-9_.]{3}$");
var phreg=new RegExp("^[0-9]{10}$");
var ruser=userreg.exec(userv);
var remail=emailreg.exec(emailv);
var rph=phreg.exec(phv);
if(ruser && remail && rph && (pwdv.length > 6))
{
alert("All values are valid");
return true;
}
else
{
if(!ruser) { alert("username
invalid");document.forms[0].user.focus();}
if(!remail) { alert("password
invalid");document.forms[0].user.focus();}
if(!rph) { alert("phone number
invalid");document.forms[0].ph.focus();}
if(pwdv.length < 6) { alert("password
invalid");document.forms[0].pwd.focus();}
return false;
}
}
Register.html
<html>
<body>
<center>
<fieldset>
<legend>Registration</legend>
<form action="Database" method="get" onSubmit="return fun()">
<pre>
Name :<input type="text" name="user" size="10"><br>
Password :<input type="password" name="pwd" size="10"><br>
E-mail :<input type="text" name="email" size="10"><br>
Phone Number :<input type="text" name="ph" size="10"><br>
<input type="submit" value="Register">
</pre>
</form>
</body>
<script src="valid.js"></script>
</html>
4.Write an HTML page including any required JavaScript that
takes a number from one text field in the range of 0 to 999 and
shows it in another text field in words. if the number is out of range,
it should show “out of range” and if it is not a number, it should
show “not a number” message in the result box

<html>
<head>
<title>Number in words</title>
<script language="javascript">
function convert()
{
var num=document.forms["frm1"].num.value;
document.forms["frm1"].words.value="";
if(isNaN(num))
{
alert("Not a Number");
}
else if (num<0 || num>999)
{
alert("Out of Range");
}
else
{
var len=num.length;
var words="";
for(var i=0;i<len;i++)
{
var n=num.substr(i,1);
switch(n)
{
case '0':words+="Zero ";break;
case '1':words+="One ";break;
case '2':words+="Two ";break;
case '3':words+="Three ";break;
case '4':words+="Four ";break;
case '5':words+="Five ";break;
case '6':words+="Six ";break;
case '7':words+="Seven ";break;
case '8':words+="Eight ";break;
default:words+="Nine ";
}
}
document.forms["frm1"].words.value=words;
}
}
</script>
</head>
<body>
<form name="frm1">
<center><h3>NUMBER IN WORDS</h3></center>
<br/>
<center>Enter a Number :<input type="text" name="num"</input><br/>
</center>
<br/>
<center><input type="button" name="inwords" value="In Words" oncli
ck="convert()"></input></center>
<br/><br/><center>Number in Words :<input type="text" name="words
"</input></center>
<br/>
</form>
</body>
</html>
5. Write a JavaScript code that displays text “TEXT-GROWING”
with increasing font size in the interval of 100ms in RED COLOR,
when the font size reaches 50pt it displays “TEXT SHRINKING” in
BLUE color. Then the font size decreases to 5pt.
<!DOCTYPE HTML>
<html>
<head>
<style>
p{
position: absolute; top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
var var1 = setInterval(inTimer, 100);
var fs = 5;
var ids = document.getElementById("demo");
function inTimer()
{
ids.innerHTML = 'TEXT GROWING';
ids.setAttribute('style', "font-size: " + fs + "px; color: red");
fs += 5;
if(fs >= 50 )
{
clearInterval(var1);
var2 = setInterval(deTimer, 1000);
}
}
function deTimer()
{
fs -= 5;
ids.innerHTML = 'TEXT SHRINKING';
ids.setAttribute('style', "font-size: " + fs + "px; color: blue");
if(fs === 5 ){
clearInterval(var2);
}
}
</script>
</body>
</html>

7.Develop and demonstrate PHP Script for the following problems:


a) Write a PHP Script to find out the Sum of the Individual Digits.
b) Write a PHP Script to check whether the given number is
Palindrome or not

1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>

8. Write a PHP program to keep track of the number of visitors visiting


the web page and to display this count of visitors, with proper headings

<?php
echo"No of Visitor is:";
$handler=fopen("file.txt","r");
$hit=(int)fread($handler,20);
fclose($handler);
$hit++;
$handler=fopen("file.txt","w");
fwrite($handler,$hit);
fclose($handler);
echo $hit;
?>.

9. Write a PHP Program to display current Date, Time and Day.

<?php

// PHP program to get the

// current date and time

echo "Current date and time is :";

// Store the date and time to

// the variable

$myDate = date("d-m-y h:i:s");

// Display the date and time

echo $myDate;
?>

10. Write the PHP programs to do the following:


a. Implement simple calculator operations.
b. Find the transpose of a matrix.
c. Multiplication of two matrices.
d. Addition of two matrices.

<html>
<head>
<style>
table, td, th {
border: 1px solid black;
width: 35%;
text-align: center;
background-color: lightgray;
}
table { margin: auto; }
input,p { text-align:right; }
</style>
</head>

<body>
<form method="post" action="prog8a.php">
<table>
<caption><h2> SIMPLE CALCULATOR </h2></caption>
<tr>
<td>First Number:</td><td><input type="text" name="num1" /></td>
<td rowspan="2"><button type="submit" name="submit"
value="calculate">Calculate</td></tr>
<tr>
<td>Second Number:</td><td><input type="text"
name="num2"/></td>
</tr>
</form>
<?php
if(isset($_POST['submit'])) // it checks if the input submit is filled
{
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
if(is_numeric($num1) and is_numeric($num2) )
{
echo "<tr><td> Addition
:</td><td><p>".($num1+$num2)."</p></td>";
echo "<tr><td> Subtraction :</td><td><p> ".($num1-
$num2)."</p></td>";
echo "<tr><td> Multiplication
:</td><td><p>".($num1*$num2)."</p></td>";
echo "<tr><td>Division :</td><td><p>
".($num1/$num2)."</p></td>";
echo "</table>";
}
else
{
echo"<script> alert(' ENTER VALID NUMBER');</script>";
}
}
?>
</body>
</html>

11. Write a PHP program named states.py that declares a variable


states with value "Mississippi Alabama Texas Massachusetts
Kansas". write a PHP program that does the following:

<html>
<body>
<?php
$states = "Mississippi Alabama Texas Massachusetts Kansas";
$b = explode(' ',$states);
echo "<br>ORIGINAL ARRAY :<br>";
foreach ( $b as $i => $value )
echo "states[$i] = $value<br>";
foreach ($b as $c)
{
$n = strlen($c);
if($c[$n-1]=='s' && $c[$n-2]=='a' && $c[$n-3]=='x') $d[0] = $c;
if($c[0]=='K' && $c[$n-1]=='s') $d[1] = $c;
if($c[0]=='M' && $c[$n-1]=='s') $d[2] = $c;
if($c[$n-1]=='a') $d[3] = $c;
}
echo "<br>RESULTANT ARRAY :<br>";
for ($i=0; $i < count($d); $i++)
echo "statesList[$i] = $d[$i]<br>";
?>
</body>
</html>

12.Write a PHP program to sort the student records which are


stored in the database using selection sort.

<?php
function selection_sort($data)
{
for($i=0; $i<count($data)-1; $i++) {
$min = $i;
for($j=$i+1; $j<count($data); $j++) {
if ($data[$j]<$data[$min]) {
$min = $j;
}
}
$data = swap_positions($data, $i, $min);
}
return $data;
}

function swap_positions($data1, $left, $right) {


$backup_old_data_right_value = $data1[$right];
$data1[$right] = $data1[$left];
$data1[$left] = $backup_old_data_right_value;
return $data1;
}
$my_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$my_array );
echo "\nSorted Array :\n";
echo implode(', ',selection_sort($my_array)). PHP_EOL;
?>
13. Write a PHP program for sending and receiving plain text
message (email).
<html>

<head>
<title>Sending HTML email using PHP</title>
</head>

<body>

<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";


$message .= "<h1>This is headline.</h1>";

$header = "From:abc@somedomain.com \r\n";


$header .= "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";

$retval = mail ($to,$subject,$message,$header);

if( $retval == true ) {


echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>

</body>
</html>
Database Management System Lab(21CSL48)

1.Consider the following schema for a Library Database:

BOOK(Book_id, Title, Publisher_Name, Pub_Year)


BOOK_AUTHORS(Book_id, Author_Name)
PUBLISHER(Name, Address, Phone)
BOOK_COPIES(Book_id, Programme_id, No-of_Copies)
BOOK_LENDING(Book_id, Programme_id, Card_No, Date_Out, Due_Date)
LIBRARY_PROGRAMME(Programme_id, Programme_Name, Address)
Write SQL queries to
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in
each Programme, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to Jun
2017.
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulation
operation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.
5. Create a view of all books and its number of copies that are currently available in the Library.

Table Creation

CREATE TABLE BOOK (


BOOK_ID INT (10) PRIMARY KEY,
TITLE VARCHAR (20),
PUB_YEAR VARCHAR (20),
PUBLISHER_NAME VARCHAR (20),
FOREIGN KEY (PUBLISHER_NAME) REFERENCES PUBLISHER (NAME) ON DELETE CASCADE);

CREATE TABLE BOOK_AUTHORS (


AUTHOR_NAME VARCHAR (20),
BOOK_ID INT (10),
PRIMARY KEY (BOOK_ID, AUTHOR_NAME),
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE);

CREATE TABLE PUBLISHER(


NAME VARCHAR(20) PRIMARY KEY,
PHONE BIG INT (20),
ADDRESS VARCHAR(100));

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 1
Database Management System Lab(21CSL48)

CREATE TABLE BOOK_COPIES(


NO_OF_COPIES INT (5),
BOOK_ID INT (10),
PROGRAMME_ID INT (10),
PRIMARY KEY(BOOK_ID,PROGRAMME_ID),
FOREIGN KEY(BOOK_ID) REFERENCES BOOK(BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (PROGRAMME_ID) REFERENCES LIBRARY_PROGRAMME
(PROGRAMME_ID) ON DELETE CASCADE);

CREATE TABLE BOOK_LENDING(


DATE_OUT DATE,
DUE_DATE DATE,
BOOK_ID INT(10),
PROGRAMME_ID INT (10),
CARD_NO INT(10),
PRIMARY KEY(BOOK_ID,PROGRAMME_ID,CARD_NO),
FOREIGN KEY(BOOK_ID) REFERENCES BOOK(BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (PROGRAMME_ID) REFERENCES
LIBRARY_PROGRAMME(PROGRAMME_ID) ON DELETE CASCADE,
FOREIGN KEY(CARD_NO) REFERENCES CARD(CARD_NO) ON DELETE CASCADE);

CREATE TABLE CARD(


CARD_NO INT(10) PRIMARY KEY);

CREATE TABLE LIBRARY_PROGRAMME(


PROGRAMME_ID INT (10) PRIMARY KEY,
PROGRAMME_NAME VARCHAR (50), ADDRESS
VARCHAR(100));

Insertion of Values to Tables


INSERT INTO BOOK VALUES (1,'DBMS','JAN-2017', 'MCGRAW-HILL');
INSERT INTO BOOK VALUES (2,'ADBMS','JUN-2016','MCGRAW-HILL');
INSERT INTO BOOK VALUES (3, 'CD','SEP-2016','PEARSON');
INSERT INTO BOOK VALUES (4,' ALGORITHMS ','SEP-2015',' MIT');
INSERT INTO BOOK VALUES (5,'OS','MAY-2016','PEARSON');

INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 1);


INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 2);
INSERT INTO BOOK_AUTHORS VALUES ('ULLMAN',3);

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 2
Database Management System Lab(21CSL48)

INSERT INTO BOOK_AUTHORS VALUES ('CHARLES', 4);


INSERT INTO BOOK_AUTHORS VALUES('GALVIN', 5);

INSERT INTO PUBLISHER VALUES ('MCGRAW-HILL', 9989076587,'BANGALORE');


INSERT INTO PUBLISHER VALUES ('PEARSON', 9889076565,'NEWDELHI');
INSERT INTO PUBLISHER VALUES ('PRENTICE HALL', 7455679345,'HYEDRABAD');
INSERT INTO PUBLISHER VALUES ('WILEY', 8970862340,'CHENNAI');
INSERT INTO PUBLISHER VALUES ('MIT',7756120238,'BANGALORE');

INSERT INTO BOOK_COPIES VALUES (10, 1, 10);


INSERT INTO BOOK_COPIES VALUES (5, 1, 11);
INSERT INTO BOOK_COPIES VALUES (2, 2, 12);
INSERT INTO BOOK_COPIES VALUES (5, 2, 13);
INSERT INTO BOOK_COPIES VALUES (7, 3, 14);
INSERT INTO BOOK_COPIES VALUES (1, 5, 10);
INSERT INTO BOOK_COPIES VALUES (3, 4, 11);

INSERT INTO BOOK_LENDING VALUES ('2017-01-01','2017-06-01', 1, 10, 101);


INSERT INTO BOOK_LENDING VALUES ('2017-01-11 ','2017-03-11', 3, 14, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-02-21','2017-04-21', 2, 13, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-03-15 ','2017-07-15', 4, 11, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-04-12','2017-05-12', 1, 11, 104);

INSERT INTO CARD VALUES (100);


INSERT INTO CARD VALUES (101);
INSERT INTO CARD VALUES (102);
INSERT INTO CARD VALUES (103);
INSERT INTO CARD VALUES (104);

INSERT INTO LIBRARY_PROGRAMME VALUES (10,'VIJAY NAGAR','MYSURU');


INSERT INTO LIBRARY_PROGRAMME VALUES (11,'VIDYANAGAR','HUBLI');
INSERT INTO LIBRARY_PROGRAMME VALUES(12,'KUVEMPUNAGAR','MYSURU');
INSERT INTO LIBRARY_PROGRAMME VALUE(13,'RAJAJINAGAR','BANGALORE');
INSERT INTO LIBRARY_PROGRAMME VALUES (14,'MANIPAL','UDUPI');

SELECT * FROM BOOK;

BOOK_ID TITLE PUB_YEAR PUBLISHER_NAME


1 DBMS Jan-2017 MCGRAW-HILL
2 ADBMS Jun-2017 MCGRAW-HILL

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 3
Database Management System Lab(21CSL48)

3 CD Sep-2016 PEARSON
4 ALGORITHMS Sep-2015 MIT
5 OS May-2016 PEARSON

SELECT * FROM BOOK_AUTHORS;

AUTHOR_NAME BOOK_ID
NAVATHE 1
NAVATHE 2
ULLMAN 3
CHARLES 4
GALVIN 5

SELECT * FROM PUBLISHER;

NAME PHONE ADDRESS


MCGRAW-HILL 9989076587 BANGALORE
MIT 7756120238 BANGALORE
PEARSON 9889076565 NEWDELHI
PRENTICEHALL 7455679345 HYEDRABAD
WILEY 8970862340 CHENNAI

SELECT * FROM BOOK_COPIES;

NO_OF_COPIES BOOK_ID PROGRAMME_ID


10 1 10
5 1 11
2 2 12
5 2 13
7 3 14
1 5 10
3 4 11
Department of Computer Science and Engineering
Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 4
Database Management System Lab(21CSL48)

SELECT * FROM BOOK_LENDING;

DATEOUT DUEDATE BOOKID PROGRAMME_ID CARDNO


2017-01-01 2017-06-01 1 10
2017-01-11 2017-03-11 3 4 101
2017-02-21 2017-04-21 2 13 101
2017-03-15 2017-07-15 4 11 101
2017-04-12 2017-05-12 1 11 104

SELECT * FROM CARD;

CARDNO
101
102
103
104
105

SELECT * FROM LIBRARY_PROGRAMME;

PROGRAMME_ID PROGRAMME_NAME ADDRESS


10 VIJAYNAGAR MYSURU
11 VIDYANAGAR HUBLI
12 KUVEMPUNAGAR MYSURU
13 RAJAJINAGAR BANGALORE
14 MANIPAL UDUPI

Queries:
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in
each Programme, etc.

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 5
Database Management System Lab(21CSL48)

SELECT B.BOOK_ID, B.TITLE, B.PUBLISHER_NAME, A.AUTHOR_NAME,


C.NO_OF_COPIES,L.PROGRAMME_ID FROM BOOK B,BOOK_AUTHORS A,BOOK_COPIES C,
LIBRARY_PROGRAMME L WHERE B.BOOK_ID=A.BOOK_ID AND B.BOOK_ID=C.BOOK_ID AND
L.PROGRAMME_ID=C.PROGRAMME_ID;

BOOK_ TITLE PUBLISHER_ AUTHOR_ NO_ PROGRAMME


ID NAME NAME OF_COPIES _ID
1 DBMS MCGRAW-HILL NAVATHE 10 10

1 DBMS MCGRAW-HILL NAVATHE 5 11

2 ADBMS MCGRAW-HILL NAVATHE 2 12

2 ADBMS MCGRAW-HILL NAVATHE 5 13

3 CD PEARSON ULLMAN 7 14

4 ALGORITHMS MIT CHARLES 1 11

5 OS PEARSON GALVIN 3 10

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to Jun
2017.
SELECT CARD_NO FROM BOOK_LENDING WHERE DATE_OUT BETWEEN '2017-01-01' AND '2017-
07-01' GROUPBY CARD_NO HAVING COUNT(*)>3;

3.Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulation
operation.

DELETE FROM BOOK WHERE BOOK_ID=3;

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 6
Database Management System Lab(21CSL48)

4.Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.

CREATE VIEW VW_PUBLICATION AS SELECT PUB_YEAR FROM BOOK;

SELECT * FROM VW_PUBLICATION;

5. Create a view of all books and its number of copies that are currently available in the Library.

CREATE VIEW VW_BOOKS AS SELECT B.BOOK_ID,B.TITLE, C.NO_OF_COPIES FROM BOOK B,


BOOK_COPIES C, LIBRARY_PROGRAMME L WHERE B.BOOK_ID=C.BOOK_ID AND
C.PROGRAMME_ID=L.PROGRAMME_ID;

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 7
Database Management System Lab(21CSL48)

SELECT * FROM VW_BOOKS;

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 8
Database Management System Lab(21CSL48)

2.Consider the following schema for Order Database:

SALESMAN(Salesman_id, Name, City, Commission)


CUSTOMER(Customer_id, Cust_Name, City, Grade, Salesman_id)
ORDERS(Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)
Write SQL queries to
1. Count the customers with grades above Bangalore’s average.
2. Find the name and numbers of all salesman who had more than one customer.
3. List all the salesman and indicate those who have and don’t have customers in their cities (Use
UNION operation.)
4. Create a view that finds the salesman who has the customer with the highest order of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must also
be deleted.

CREATE TABLE SALESMAN ( SALESMAN_ID


INT(4)PRIMARY KEY, NAME VARCHAR (20),
CITY VARCHAR(20),
COMMISSION VARCHAR(20));

CREATE TABLE CUSTOMER (


CUSTOMER_ID INT(5) PRIMARY KEY,
CUST_NAME VARCHAR (20),
CITY VARCHAR (20),GRADE INT(4),
SALESMAN_ID INT(6),
FOREIGN KEY(SALESMAN_ID) REFERENCES SALESMAN(SALESMAN_ID) ON DELETE SET NULL);

CREATE TABLE ORDERS (


ORD_NO INT (5) PRIMARY KEY,
PURCHASE_AMT DECIMAL(10,2),
ORD_DATE DATE,
CUSTOMER_ID INT (4),
SALESMAN_ID INT(4),
FOREIGN KEY(CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID) ON DELETE CASCADE,
FOREIGN KEY(SALESMAN_ID) REFERENCES SALESMAN (SALESMAN_ID) ON DELETE CASCADE);

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 9
Database Management System Lab(21CSL48)

INSERT INTO SALESMAN VALUES(101,'RICHARD','LOS ANGELES','18%');


INSERT INTO SALESMAN VALUES(103,'GEORGE','NEWYORK','32%');
INSERT INTO SALESMAN VALUES(110,'CHARLES','BANGALORE','54%');
INSERT INTO SALESMANVALUES(122,'ROWLING','PHILADELPHIA','46%');
INSERT INTO SALESMAN VALUES(126,'KURT','CHICAGO','52%');
INSERT INTO SALESMAN VALUES(132,'EDWIN','PHOENIX','41%');

INSERT INTO CUSTOMER VALUES(501,'SMITH','LOS ANGELES',10,103);


INSERT INTO CUSTOMER VALUES(510,'BROWN','ATLANTA',14,122);
INSERT INTO CUSTOMER VALUES(522,'LEWIS','BANGALORE',10,132);
INSERT INTO CUSTOMER VALUES(534,'PHILIPS','BOSTON',17,103);
INSERTINTO CUSTOMERVALUES(543,'EDWARD','BANGALORE',14,110);
INSERT INTO CUSTOMER VALUES(550,'PARKER','ATLANTA',19,126);

SELECT * FROM SALESMAN;

SELECT * FROM CUSTOMER;

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 10
Database Management System Lab(21CSL48)

SELECT * FROM ORDERS;

Queries
1. average.
SELECT GRADE,COUNT(CUSTOMER_ID)FROM CUSTOMER
GROUPBY GRADE
HAVING GRADE>(SELECT AVG(GRADE) FROM CUSTOMER WHERE
CITY='BANGALORE');

SELECTGRADE,COUNT(DISTINCTCUSTOMER_ID) FROM
CUSTOMER GROUP BY GRADE

HAVINGGRADE>(SELECTAVG(GRADE)FROMCUSTOMER WHERE
CITY='BANGALORE');

2. Find the name and numbers of all salesmen who had more than one customer.
SELECT SALESMAN_ID,NAME FROM
SALESMAN A
WHERE 1<(SELECTCOUNT(*) FROM CUSTOMER WHERE
SALESMAN_ID=A.SALESMAN_ID)

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 11
Database Management System Lab(21CSL48)

OR
SELECT S.SALESMAN_ID,NAME,FROM CUSTOMER C,SALESMAN S
WHERE S.SALESMAN_ID=C.SALESMAN_ID GROUP BY
C.SALESMAN_ID HAVING COUNT(*)>1

3. List all the salesman and indicate those who have and don’t have customers in their cities (Use
UNION operation.)
SELECT S.SALESMAN_ID,NAME,CUST_NAME,COMMISSION FROM SALESMAN S,CUSTOMER C
WHERE S.CITY=C.CITY UNION
SELECT SALESMAN_ID,NAME,'NOMATCH',COMMISSION FROM SALESMAN WHERE NOT CITY = ANY
(SELECT CITY FROM CUSTOMER) ORDER BY 2 DESC;

4.Create a view that finds the salesman who has the customer with the highest order of a day.
CREATE VIEW VW_ELIT SALESMAN AS
SELECT B.ORD_DATE,A.SALESMAN_ID,A.NAME FROM SALESMAN A,ORDERS B WHERE
A.SALESMAN_ID = B.SALESMAN_ID AND B.PURCHASE_AMT=(SELECT MAX(PURCHASE_AMT) FROM
ORDERS C WHERE C.ORD_DATE=B.ORD_DATE);

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 12
Database Management System Lab(21CSL48)

SELECT * FROM VW_ELIT SALESMAN;

5. Demonstrate the DELETE operation by removing salesman with id 1000.All his orders must also be
deleted.

DELETE FROM SALESMAN WHERE SALESMAN_ID=101;

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University, Kalaburagi Page 13
Database Management System Lab(21CSL48)

3.Consider the schema for Movie Database:

ACTOR(Act_id, Act_Name, Act_Gender)


DIRECTOR(Dir_id, Dir_Name, Dir_Phone)
MOVIES(Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)
MOVIE_CAST(Act_id, Mov_id, Role)
RATING(Mov_id, Rev_Stars)
Write SQL queries to
1. List the titles of all movies directed by ‘Hitchcock’.
2. Find the movie names where one or more actors acted in two or more movies.
3. List all actors who acted in a movie before 2000 and also in a movie after 2015(use JOIN
operation).
4. Find the title of movies and number of stars for each movie that has at least one rating
and find the highest number of stars that movie received. Sort the result by movie title.
5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 14
Database Management System Lab(21CSL48)

4.Consider the schema for College Database:

STUDENT(USN, SName, Address, Phone, Gender)


SEMSEC(SSID, Sem, Sec) CLASS(USN, SSID)
COURSE(Subcode, Title, Sem, Credits)
IAMARKS(USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)

Write SQL queries to


1. List all the student details studying in fourth semester ‘C’ section.
2. Compute the total number of male and female students in each semester and in each
section.
3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in all Courses.
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for all students.
5. Categorize students based on the following criterion: If FinalIA = 17 to 20 then CAT =
‘Outstanding’ If FinalIA = 12 to 16 then CAT = ‘Average’ If FinalIA< 12 then CAT =
‘Weak’ Give these details only for 8th semester A, B, and C section students

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 15
Database Management System Lab(21CSL48)

5.Consider the schema for Company Database:

EMPLOYEE(SSN, Name, Address, Sex, Salary, SuperSSN, DNo)


DEPARTMENT(DNo, DName, MgrSSN, MgrStartDate)
DLOCATION(DNo,DLoc)
PROJECT(PNo, PName, PLocation, DNo)
WORKS_ON(SSN, PNo, Hours)
Write SQL queries to
1. Make a list of all project numbers for projects that involve an employee whose last name
is ‘Scott’, either as a worker or as a manager of the department that controls the
project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department
4. Retrieve the name of each employee who works on all the projects controlled by
department number 5 (use NOT EXISTS operator).
5. For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than Rs.6,00,000.

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 16
Database Management System Lab(21CSL48)

6. Develop PL/SQL program using PROCEDURE


declare
first number:=0;
second number:=1;
third number;
n number:=&n;
i number;
begin
dbms_output.put_line('fibonacci series is :');
dbms_output.put_line(first);
dbms_output.put_line(second);
for i in 2..n
loop
third:=first+second;
first:=second;
second:=third;
dbms_output.put_line(third);
end loop;
end;
/
Output:
Enter the value for n:4
Fibonacci series is:
0
1
1
2
3

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 17
Database Management System Lab(21CSL48)

7.Develop PL/SQL program using FUNCTIONS


declare
num number;
factorial number;
function fact(x number)
return number
is
f number;
begin
if x=0 then
f:=1;
else
f:=x*fact(x-1);
end if;
return f;
end;
begin
num:=6;
factorial:=fact(num);
dbms_output.put_line('factorial '||num||'is'||factorial);
end;
/

Output:
Factorial of 6 is 720
Procedure successfully completed

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 18
Database Management System Lab(21CSL48)

8. Develop PL/SQL program using CURSOR


Create table customers(id int,name varchar(10),age int,address varchar(20),salary float);
Insert into customers values(1,’sita’,32,’ahmedabad’,2000.00);
Insert into customers values(2,’ram’,25,’delhi’,1500.00);
Insert into customers values(3,’john’,23,’Kota’,2000.00);
Insert into customers values(4,’mary’,25,’mumbai’,6500.00);
Insert into customers values(5,’bon’,27,’bhopal’,8500.00);
Select * from customers;

id name age address salary


1 Sita 32 Ahmedabad 2000.00
2 Ram 25 Delhi 1500.00
3 John 23 Kota 2000.00
4 Mary 25 Mumbai 6500.00
5 bon 27 bhopal 8500.00

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

Output:
5 customers selected
Procedure successfully completed

id name Age address salary


1 Sita 32 Ahmedabad 2500.00
2 Ram 25 Delhi 2000.00
Department of Computer Science and Engineering
Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 19
Database Management System Lab(21CSL48)

3 John 23 Kota 2500.00


4 Mary 25 Mumbai 7000.00
5 bon 27 bhopal 9000.00

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 20
Database Management System Lab(21CSL48)

9.Develop PL/SQL Programs using TRIGGERS

Create table passenger (id int,name varchar(10),ticket_no int);


Insert into passenger values(1,’sita’,32);
Insert into passenger values(2,’ram’,25);
Insert into passenger values(3,’john’,56);
Insert into passenger values(4,’mary’,45);
Select * from passenger;

id Name Ticket_no
1 Sita 32
2 Ram 25
3 John 56
4 Mary 45

CREATE OR REPLACE TRIGGER UPDATECHECK

BEFORE UPDATE ON PASSENGER

FOR EACH ROW

WHEN (NEW.TICKET_NO > 60)

BEGIN :NEW.TICKET_NO := :OLD.TICKET_NO;

dbms_output.put_line('updcheck called');

END;

Output:

Trigger Created

10.Develop PL/SQL programs using PACKAGES

Create table customers(id int,name varchar(10),age int,address varchar(20),salary float);


Department of Computer Science and Engineering
Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 21
Database Management System Lab(21CSL48)

Insert into customers values(1,’sita’,32,’ahmedabad’,2000.00);


Insert into customers values(2,’ram’,25,’delhi’,1500.00);
Insert into customers values(3,’john’,23,’Kota’,2000.00);
Insert into customers values(4,’mary’,25,’mumbai’,6500.00);
Insert into customers values(5,’bon’,27,’bhopal’,8500.00);
Select * from customers;

id Name age Address salary


1 Sita 32 Ahmedabad 2000.00
2 Ram 25 Delhi 1500.00
3 John 23 Kota 2000.00
4 Mary 25 Mumbai 6500.00
5 Bon 27 Bhopal 8500.00

CREATE PACKAGE cust_sal AS


PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/

Output:

Package Created

CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_id customers.id%TYPE) IS


c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Output:

Package Body Created

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 22
Database Management System Lab(21CSL48)

DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/

Output:

Enter the value of cc_id:3

Salary:2500

Procedure successfully completed

Department of Computer Science and Engineering


Faculty of Engineering and Technology(Ex-Women)
Sharnbasva University,Kalaburagi Page 23
PYTHON LAB MANUAL(22CSL48) 2023-2024

VISION
➢ Enhancing the horizon of world knowledge by promoting international understanding through
imparting quality education and creating value added skill based human resource.
➢ We aspire to become top ranking national and international centre of excellence producting high
Caliber leaders and captains of industry.
➢ “sakala jeevaathmarige lesane bayasuva” (wishing the worldly good and betterment of all the living
Beigns) is our moto

MISSION
➢ Achieving academic excellence through innovatively designed, research intensive, industry oriented
education.

➢ Imbibing the culture of Independent thinking, Independent writing, Independent speaking and
Independent living among the students in all the activities.
➢ Foster the spirit of National development and develop global competences. Nurture creativity and
encourage entrepreneurship and provide an education with rigor and relevance.
➢ Provide academically excellent, time efficient, and cost effective higher education. Provide an
education which enhances the ability of students to learn through out the life.
➢ Ensure freedom of thought and expression in a campus without discrimination
➢ Encourage the spirit of questioning and ensure close inter-relationship between Teaching, Scholarship
and Research.
➢ Develop and deliver distinctive and value driven academic programme that are flexible and
responsible to Local, National and International needs.
➢ Cultivate academic, business and community driven partnership that positions the University as a
leading choice for adult learners.
➢ To work effectively with other institutions and organization, where such partnerships can lead to

understanding research and teaching.

Page 1 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024

VISION OF THE DEPARTMENT

Aspire to become a centre of excellence for quality technical education and research by keeping pace with
new technologies to empower girl students to lead and excel in the field of computer science & engineering
along with ethical principles & a sense of social responsibility.

MISSION OF THE DEPARTMENT

✓ To impart academic excellence, encourage research and innovation in Computer science and
engineering
✓ To educate the students with knowledge and skills , encourage students to address societal problems
through IT solutions
✓ To prepare students to develop entrepreneurship skills with proper ethical values and a desire to
pursue life-long learning

PROGRAM EDUCATIONAL OBJECTIVES (PEO)

PEO1: To provide knowledge for students to formulate ,analyze and solve engineering challenges to real
life problems.

PEO2 : To prepare the students to be ready for industry/Research and Development/Academic profession
so as to meet changing needs.

PEO3: To acquire life-long learning skills, managerial, leadership skills and entrepreneurial ability in
students to inculcate professional,ethical attitudes, communication , technical writing, team working
attitude & an ability for relating engineering issues to social context.

PROGRAM SPECIFIC OUTCOMES (PSO’s)


Graduates of the Computer Science and Engineering program will be able to

Page 2 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
PSO1 - Pertain current knowledge and adapting to emerging applications of Mathematics, Science and

Engineering fundamentals in the field of Computer Science and Engineering

PSO2 - Apply standard Software Engineering practices and strategies in real-time software project

development areas related to algorithms, networking, web design, cloud computing, IoT and data analytics

of varying complexity using open-source programming environment or commercial environment to

deliver quality product for the organization success.

PSO3 - Ability to understand professional, legal, cultural, social issues and its responsibilities for

professional development

PROGRAM OUTCOMES

PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals

and computing to solve Computer Science and Engineering related problems.

PO2: Problem Analysis : Identify, formulate , Research literature and analyse complex engineering

problems reaching substantiated conclusions using first principles of mathematics, natural sciences and

engineering sciences.

PO3: Design / Development of Solutions: Design solutions for complex engineering problems and design

system components or processes that meet the specified needs with appropriate consideration for public

health and safety, and cultural ,societal

PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research methods

including design of experiments, analysis and interpretation of data, and synthesis of the information to

provide valid conclusions.

PO5: Modern tool usage :Create, select and apply appropriate techniques, resources, and modern

engineering and IT tools including prediction and modelling to complex engineering activities related to

Computer Science and Engineering with an understanding of the limitations.

Page 3 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,

health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional

engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional engineering solutions in

societal and environmental contexts, and demonstrate the knowledge of and need for sustainable

development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms

of the engineering practice.

PO9: Individual and Team Work: Function effectively as an individual and as a member or leader to

diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the engineering

community and with society at large, such as, being able to comprehend and write effective report and

design documentation, make effective presentations, and give and receive clear instructions.

PO11: Project Management and Finance: Demonstrate knowledge and understanding of the engineering

and management principles and apply these to one’s own work, as a member and leader in a team, to

manage projects and in multidisciplinary environments.

PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to engage in

independent and life-long learning in the broadest context of technological change

COURSE OUTCOMES (CO)

Page 4 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024

CO1 Demonstrate theoretical concepts of python through series of experiments

CO2 Develop a program using software tools

CO3 Debug and troubleshoot software issues effectively

CO4 Analyze the data and interpret the results

CO5 Prepare a well organized laboratory report

CO to PO & PSO MAPPING


PO1 PO PO3 P PO PO PO PO PO PO1 PO1 PO1 PSO1 PSO2 PSO3
2 O 5 6 7 8 9 0 1 2
4

CO1 3 2 2 1 2 3 3 3
CO2 1 2 3 3 1 2 3 2 2
CO3 1 3 1 2 2 2 3
CO4 2 1 1 3 2 2 2 2
CO5 1 2 3 2 1 1 3
AVG 1.4 1.6 1 0.6 1 0.4 1.2 2 2.2 2 2.6

LABORATORY

General Lab Guidelines:

Page 5 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
1. Conduct yourself in a responsible manner at all times in the laboratory. Intentional misconduct will lead
to exclusion from the lab.
2. Do not wander around, or distract other students, or interfere with the laboratory experiments of other
students.
3. Read the handout and procedures before starting the experiments. Follow all written and verbal
instructions carefully.
4. If you do not understand the procedures, ask the instructor or teaching assistant. Attendance in all the
labs is mandatory, absence permitted only with prior permission from the Class teacher.
5. The workplace has to be tidy before, during and after the experiment.
6. Do not eat food, drink beverages or chew gum in the laboratory.
7. Every student should know the location and operating procedures of all Safety equipment including
First Aid Kit and Fire extinguisher
DO’S
▪ Be punctual to the laboratory classes with proper dress code.
▪ Before starting the system, check for proper electrical and network connections.
▪ Follow the instructions of the staff.
▪ Follow proper code of conduct and ethics.
▪ Any problem prevalence must be brought to the notice of the concerned staff.
▪ Use only assigned computer/laptop and turn off the computer/laptop before leaving.
▪ Submit the completed record on time.
DON’T’S
▪ Don’t use mobile phones inside the laboratories.
▪ Don’t plug pen-drive or any storage devices on the system.
▪ Don’t download or install any software in the system.
▪ Don’t modify, or delete any existing files in the system.
▪ Don’t play the game in the laboratory.
▪ Don’t change any system settings.
▪ Don’t damage/remove/disconnect any part /labels/cables in the system.
LIST OF PROGRAMMS
Course Learning objectives: This course will enable students to:

Page 6 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
• Develop program to solve real world problems using python programming.
• Develop the programs using the concepts of control statements, data structures & files.
• Apply features of object-oriented and Numpy, pandas package to develop computationally
intensive programming & interpret the data.
Part-A

No. Title of the experiment Expected


Skill /Ability
a. Develop a program to read the student’s details like Name, USN, and Basics of
Marks in three subjects. Display the student’s details, total marks, and Python
percentage with suitable messages.
b. Develop a program to read the name and year of birth of a person.
1.
Display whether the person is a senior citizen or not.
c. Read N numbers from the console and create a list. Develop a
program to print mean, variance, and standard deviation with suitable
messages.

a. Write a program to demonstrate different numbered data types in Basics of


Python and perform a different arithmetic operation on numbers in Python
Python.
b. Write a program to create, concatenate and print a string and access a
2. sub-string from a given string.
c. Write a Python script to print the current date in the following format
“Sun May 29 02:26:23 IST 2017”.
d. Read a multi-digit number (as char) from the console. Develop a
program to print the frequency of each digit with suitable
messages.
a. Develop a program to find the largest of three numbers Conditional
b. Develop a program to generate a Fibonacci sequence of length (N). Statements
Read N from the console.
3.
c. Write a program to calculate the factorial of a number. Develop a
program to compute the binomial coefficient (Given N and
R).
a. Implementing programs using Functions (Largest number in a list, area Functions
of shape)
4. and
b. implementing a real-time/technical application using Exception
handling (Divide by Zero error, Voter’s age validity, student mark range Exception
validation) Handling

Page 7 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
Using Regular expressions, develop a Python program to
5
a. Identify a word with a sequence of one upper case letter followed by
lower case letters.
b. Find all the patterns of “1(0+)1” in a given string.

a. SET1 and SET2 are two sets that contain unique integers. SET3 is to Create and
6 Perform
be created by taking the union or intersection of SET1 and SET2 using
the user-defined function Operation (). Perform either union or Union and
intersection
intersection by reading the choice from the user. Do not use built-in
operations on
function union () and intersection () and also the operators “|” and “&”. sets
b. The Dictionary “DICT1” contains N Elements and each element in the
dictionary has the operator as the KEY and operands as VALUES. Create a
Perform the operations on operands using operators stored as keys. Dictionary and
Display the results of all operation operates using
userdefineded
function
Implementing programs using Strings. (Reverse, palindrome, character String
7 count, replacing characters)
operations

a. Develop a program to print the 10 most frequently appearing words File


8
in a text file. [Hint: Use a dictionary with distinct words and their frequency Handling
of occurrences. Sort the dictionary in the reverse order of frequency and
display dictionary slice of first 10 items]
b. Develop a program to sort the contents of a text file and write the
sorted contents into a separate text file. [Hint: String method strip(), list
method sort(), append(), and file method open(), readlines(), and write()].
c. Develop a program to backing up a given Folder (Folder in a current
working directory) into a ZIP File by using relevant modules and suitable
methods.
Develop a program that uses class Students which prompts the User to Classes and
9 Objects
enter marks in three subjects and calculate total marks, Percentage and
display the scorecard details. [Hint: Use a list to store the marks in three usability
subjects and total marks. Use_init() method to initialize name, USN and
the lists to store marks and total, Use getMarks() method to read marks
into the list, and display() method to display the scorecard details.]
Implementing program using modules and python Standard Libraries Pandas,Numpy
10 ,Matplotlib,Sci
(pandas, Numpy, Matplotlib, Scipy)
py,Usability

Page 8 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024

1. INTRODUCTION TO PYTHON

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.

• Python is Interpreted − Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL and
PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.

Running Python code


Python is an interpreted language, which reduces the edit-test-debug cycle because there's no compilation
step required. In order to run Python apps, you need a runtime environment/interpreter to execute the code.
Most of the runtime environments support two ways to execute Python code:
Interactive mode: In this mode, each command you type is interpreted and executed immediately, and you
see the results each time you press ENTER. The interactive mode is the default mode if you don't pass a
filename to the interpreter.
Script mode: In script mode, you put a set of Python statements into a text file with a .py extension. You
then run the python interpreter and point it at the file. The program is executed line by line, and the output
is displayed. There's no compilation step, as shown in the following diagram:

Page 9 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024

Python implementations
Python is licensed under the OSI open-source license, and there are several implementations available
depending on your needs. Here are a few of the options available:

CPython, the reference implementation: The most popular is the reference implementation (CPython),
available from the Python website. CPython is commonly used for web development, application
development, and scripting. There are install packages for Windows and macOS. Linux users can install
Python using built-in package managers such as apt, yum, and Zypper. There's also an online playground
where you can try Python statements right on the website. Finally, the complete source code is available,
allowing you to build your own version of the interpreter.
Anaconda: Anaconda is a specialized Python distribution tailored for scientific programming tasks, such
as data science and machine learning. Check out more details on Anaconda here.
Iron Python: Iron Python is an open-source implementation of Python built on the .NET runtime. Learn
more about IronPython.
Jupyter Notebook: Jupyter Notebook is a web-based interactive programming environment that supports
various programming languages, including Python. Jupyter Notebooks are widely used in research and
academia for mathematical modeling, machine learning, statistical analysis,

Page 10 of
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024

History of Python

Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.

Python Features

ython's features include −

• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.

Page 11 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

• PEasy-to-read − Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain − Python's source code is fairly easy-to-maintain.

• A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.

• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs than
shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed
below −

• It supports functional and structured programming methods as well as OOP.

• It can be used as a scripting language or can be compiled to byte-code for building


large applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

2. INSTALLATION OF PYTHON

Page 12 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

Step:1 Visit the Anaconda downloads page¶


Go to the following link: Anaconda.com/downloads

Step 2: Select Windows


Select Windows where the three operating systems are listed.

Step 3:Download.

Step 5:Open and run the installer¶


Once the download completes, open and run the .exe installe

Page 13 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

Page 14 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

Step 6: Create a Conda Environment


conda create --name myenv

Step 7: Activate the Conda Environment


After creating the environment, activate it using the following command:conda activate myenv

Step 8: Install Spyder in the Conda Environment


Now, you can install Spyder in the activated conda environment using the following command:

conda install spyder

Step 8: Launch Spyder


Finally, you can launch Spyder using the following command: Spyder

Page 15 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

BASICS OF PYTHON

Writing your first Python Program


In Python, the print function, which is one of more than 60 functions built into the language, outputs text
to the screen.The following statement displays "Hello World!" on the screen:
print('Hello World!')
The argument passed to print is a string, which is one of the fundamental data types in Python used to
store and manage text. By default, print outputs a newline character at the end of the line, so that a
subsequent call to print starts on the next line.
Output
Hello World!

Comments in Python
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of
the program. Also, Comments enhance the readability of the code and help the programmers to understand
the code very carefully.
# sample comment # This is Python Comment name = "SUK" print(name)
Output
SUK

Keywords in Python
Keywords in Python are reserved words that can not be used as a variable name, function name, or any
other identifier.
KEYWORDS:
and,false,nonlocal,as,finally,not,assert,for,or,break,from,pass,class,global,raise,continue,if,return,
def,import,True,del,is,try,elif,in,while,else,lambda,with,except,none,yield

Python Variable
Python Variable is containers that store values. Python is not “statically typed”. An Example of a Variable
in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a
variable, it can be referred to by that name.

Page 16 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
Rules for Python variables
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
The reserved words(keywords) in Python cannot be used to name the variable in Python.
Example
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A strin
name = "John"
print(age)print(salary)print(name)

Output
45
1456.8
John
Python Data Types
Data types are the classification or categorization of data items. It represents the kind of value that tells
what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are classes and variables are instances (objects) of these classes.

Example: This code assigns variable ‘x’ different values of various data types in Python.

Page 17 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
x = "Hello World" # string ,x = 50 # integer, x = 60.5 # float ,x = 3j # complex ,x = ["SUK", "FETW",
"CSE"] # list, x = ("SUK", "FETW", "CSE") # tuple ,x = {"name": "Suraj", "age": 24} # dict ,x =
{"geeks", "for", "geeks"} # set ,x = True # bool ,x = b"Geeks" # binary
Reading keyboard input

Many programs are interactive. Supporting interactivity means you have a program that runs differently
depending on the input. The person inputting data to a program is usually a user, but it can be another
program. There are many ways to send input to a program; two common ways are via a graphical interface
or a console.
User input
For reading input from the keyboard, Python provides the input() function. input() reads what the user
types on the keyboard and returns it as a string. Here's an example that combines input() and print() to
capture a person's name and display it on the screen:

name = input('Enter your name:')


print(name)
The string passed as an argument to the input function is the prompt the user will see. In this example,
you're asking the user to type their name ('Enter your name'). Once the user types a name and presses Enter,
the input function will return. The function's return value is the text the user typed, and that text is assigned
to the variable named name. The name variable is then used as an input or argument to the print function,
which will output the name the user entered.
You can also call the input function without a parameter:

print('What is your name?')


name = input()
print(name)
This program will behave almost the same as the first one. The difference is that print (by default) adds a
newline to the output.
Reading numbers as input
The input function always returns the typed value as a string (text). This choice makes sense because the
user can enter whatever value they like. Even if the input is a valid number, it's still returned as a string

Page 18 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
type from the input function. For example:

x = input('Enter a number: ')


print(type(x))
Running this code and entering the value '5' would display <class 'str'>, even though the value itself is
numeric. To turn the value into a true integer variable, you can use the int() function:

x = int(input('Enter a number: '))


print(type(x))
This code will output <class 'int'> for the value '5'.
Working with strings
Along with numbers, strings are among the most commonly used data types. A string is a collection of
zero or more characters. Strings are commonly declared using single quotation marks, but you can also
use double quotation marks:
x = 'This is a string'
print(x) # outputs: This is a string
print(type(x)) # outputs: <class 'str'>
y = "This is also a string"
You can add strings to other strings—an operation known as "concatenation"—with the same + operator
that adds two numbers:
x = 'Hello' + ' ' + 'World!'
print(x) # outputs: Hello World!
You learn more about strings in another lesson, including how to parse them and how to manipulate them
in various ways. You also learn about other important data types such as lists, which store collections of
data and are frequently used to hold collections of strings.
Converting numbers to strings
You can go the other direction as well. The str() method will take an integer or float value and turn it into
a string. Calling the str() method is needed if you want the below code example to work. The conversion
ensures the integer, in its string form, is concatenated to the string on the left.
x=5
print('The number is ' + str(x))

Page 19 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables.
These are standard symbols used for the purpose of logical and arithmetic operations. In this article, we
will look into different types of Python operators.
Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction,
multiplication, and division.
Precedence of Arithmetic Operators
The precedence of Arithmetic Operators in Python is as follows:
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
Example
Python
a = 9b = 4add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b print(add) print(sub) print(mul) print(mod) print(p)

Output
13
5
36
1
6561
Logical Operators
Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to

Page 20 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
combine conditional statements.
Python
a = Trueb = Falseprint(a and b) print(a or b) print(not a)

Output
False
True
False
Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on
binary numbers.
Python
a = 10b = 4print(a & b) print(a | b) print(~a) print(a ^ b) print(a >> 2) print(a << 2)

Output
0
14
-11
14
2
40
Assignment Operators
Python Assignment operators are used to assign values to the variables.
Python
a = 10b = a print(b) b += a print(b) b -= a print(b) b *= a print(b) b <<= a print(b)

Output
10
20
10
100

Page 21 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
102400
Python If Else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But if we want to do something else if the condition is false, we can use the
else statement with the if statement to execute a block of code when the if condition is false.
Example 1: Python IF-Else

i = 20if (i < 15):


print("i is smaller than 15")
print("i'm in if Block") else:
print("i is greater than 15")
print("i'm in else Block") print("i'm not in if and not in else Block")

Output
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
Example 2:
Python if-elif-else ladder
i = 20if (i == 10):
print("i is 10") elif (i == 15):
print("i is 15") elif (i == 20):
print("i is 20") else:
print("i is not present")

Output
i is 20
Python For Loop
Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like String,
Tuple, List, Set, or Dictionary. Here we will see a “for” loop in conjunction with the range() function to
generate a sequence of numbers starting from 0, up to (but not including) 10, and with a step size of 2. For

Page 22 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
each number in the sequence, the loop prints its value using the print() function.
Python
for i in range(0, 10, 2):
print(i)

Output
0
2
4
6
8

Python While Loop


In this example, the condition for while will be True as long as the counter variable (count) is less than 3
# Python program to illustrate while loop count = 0while (count < 3):
count = count + 1
print("Hello students")
Output
Hello students
Hello students
Hello students
Also See: Use of break, continue and pass in Python

Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Page 23 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

Note: There are mainly two types of functions in Python.


Built-in library function: These are Standard functions in Python that are available to use.
User-defined function: We can create our own functions based on our requirements.
Example

# A simple Python function to check# whether x is even or odd


def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

Page 24 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

1 a. Develop a program to read the students details like Name, USN, and Marks in three
subjects. Display the student’s details, total marks and percentage with suitable messages.
name=str(input("enter the name of the student: "))
usn=str(input("enter the usn of the student: "))
m1=int(input("enter the marks of subject 1: "))
m2=int(input("enter the marks of subject 2: "))
m3=int(input("enter the marks of subject 3: "))
#m4=int(input("enter the marks of subject 4:"))
#m5=int(input("enter the marks of subject 5:"))

total=m1+m2+m3
per=total/3
print("total:",total)
print("percentage:",per)
if(per>=60):
print("first division")
elif(per>=50 and per<=59):
print("second division:")
elif(per>=40 and per<=49):

print("third division:")
else:
print("fail...")

Page 25 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

OUTPUT

== case – 1==

enter the name of the student: AMBIKA


enter the usn of the student: SW20AIM001
enter the marks of subject 1: 88
enter the marks of subject 2: 99

enter the marks of subject 3: 78


total: 265

percentage: 88.33333333333333 first


division

==case -2==

enter the name of the student: GANGA enter


the usn of the student: SW20AIM007 enter
the marks of subject 1: 55

enter the marks of subject 2: 45


enter the marks of subject 3: 45
total: 145

percentage: 48.333333333333336
third division:

Page 26 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

1b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not

name=str(input("enter the name of the person:"))


birth_year=int(input("Enter Year of Birth:"))
current_year=int(input("Enter Current Year :"))
age=current_year-birth_year
if (age>60): print("Senior")

else:

print("Not Senior")

OUTPUT

enter the name of the person:AMBIKA


Enter Year of Birth:2003
Enter Current Year :2023
Not Senior

enter the name of the person:GANGA


Enter Year of Birth:1947
Enter Current Year :2023
Senior

Page 27 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

1c. Read N numbers from the console and create a list. To find mean, variance and standard
deviation of given numbers
import statistics a
= list()
number = int(input( "Enter the number of elements you want: ")) print
('Enter numbers in array: ')

for i in range(int(number)):

n = input( "number : ")


a.append ( int ( n ))

print("Given 'n' numbers: ")


print(a)

m = statistics.mean ( a )

v = statistics.variance ( a ) st
= statistics.stdev ( a ) print(
"Mean: ",m)
print( "Variance: ",v)

print( "Standard Deviation: ",st)

OUTPUT

Enter the number of elements you want: 3


Enter numbers in array:
number : 3

number : 4

number : 5

Given 'n' numbers: [3,


4, 5]

Mean: 4
Variance: 1

Standard Deviation: 1.0

Page 28 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

2a. Write a program to demonstrate different number data types in python and perform
different Arithmetic operations on numbers in python.
a=10 b=8.5
c=2.05j
print("a is type of",type(a))

print("b is type of",type(b))


print("c is type of",type(c))

num1=int(input("enter first number:"))


num2=int(input("enter second number:")) print("addition of

num1 and num2:",num1+num2) print("subtraction of num1


and num2:",num1-num2) print("multiplication of num1 and
num2:",num1*num2) print("division of num1 and
num2:",num1/num2) print("remainder of num1 and
num2:",num1%num2) print("exponent of num1 and
num2:",num1**num2)
print("floored division of num1 and num2:",num1//num2)

OUTPUT

a is type of <class 'int'>

b is type of <class 'float'>

c is type of <class 'complex'>


enter first number:6
enter second number:7 addition of

num1 and num2: 13


subtraction of num1 and num2: -1

multiplication of num1 and num2: 42

division of num1 and num2: 0.8571428571428571


remainder of num1 and num2: 6

exponent of num1 and num2: 279936floored division of num1 and num2: 0

Page 29 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

2b. Write a program to create, concatenate and print a string and accessing sub-string from a
given string.'''

s1=input("Enter first String : ")


s2=input("Enter second String : ")
print("First string is : ",s1)
print("Second string is : ",s2)
print("concatenations of two strings :",s1+s2)
print("Substring of given string :",s1[1:4])

OUTPUT

Enter first String : MADAM


Enter second String : MAM
First string is : MADAM
Second string is : MAM

concatenations of two strings : MADAMMAM


Substring of given string : ADA

Page 30 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

2c. Write a python script to print the current date in the following format Sun May 29

02:26:23 IST 2017

import time;
ltime=time.localtime();

print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime)); #returns the formatted time


'''

%a : Abbreviated weekday name.

%b : Abbreviated month name.

%d : Day of the month as a decimal number [01,31].

%H : Hour (24-hour clock) as a decimal number [00,23].

%M : Minute as a decimal number [00,59].

%S : Second as a decimal number [00,61].

%Z : Time zone name (no characters if no time zone exists).

%Y : Year with century as a decimal number.'''

OUTPUT

====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/tm.py ======


Tue Mar 28 16:30:08 India Standard Time 2023

Page 31 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

2d. Read a multi-digit number (as char) from the console.


Develop a program to print the frequency of each digit suitable for messages

. def char_frequency(str1):
dict = {}

for n in str1:

keys = dict.keys() if

n in keys:

dict[n] += 1
else:
dict[n] = 1
return dict

num = input("Enter the multi digit number: ")


print(char_frequency(num))

OUTPUT

Enter the multi digit number: hello


{'h': 1, 'e': 1, 'l': 2, 'o': 1}

Page 32 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

3a. ''' Write a python program to find largest of three numbers '''
num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))


num3 = int(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):

largest = num1

elif (num2 > num1) and (num2 > num3):

largest = num2
else:

largest = num3

print("The largest number is",largest)

OUTPUT

====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/P3B.PY =====

Enter first number: 8


Enter second number: 9

Enter third number: 7 The


largest number is 9

Page 33 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

3b. Develop a program to generate Fibonacci Sequence of length(N). Read N from the console

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1

count = 0

# check if the number of terms is valid if


nterms <= 0:

print("Please enter a positive integer") # if


there is only one term, return n1
elif nterms == 1:

print("Fibonacci sequence upto",nterms,":") print(n1)

# generate fibonacci sequence


else:
print("Fibonacci sequence:") while

count < nterms:


print(n1)

nth = n1 + n2

# update values n1
= n2
n2 = nth

count += 1

OUTPUT

How many terms? 4


Fibonacci sequence: 0
1
1
2

Page 34 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

3c. Write a function to calculate the factorial of a number. Develop a program to compute the
binomial coefficient (Given N and R)

print("enter a number:",end='') try:


num=int(input()) fact=1

for i in range(1,num+1):

fact=fact*i

print("\n factorial of",num,"=",fact)


except ValueError:
print("\n invalid input!")

def binomialCoeff(n, k):


if k > n:

return 0

if k == 0 or k == n:

return 1

# Recursive Call

return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)

n=5

k=2

Print(“value of C(%d,%d) is (%d)” %(n,k)))

Page 35 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

OUTPUT

enter a number:4
factorial of 4 = 1
factorial of 4 = 2
factorial of 4 = 6
factorial of 4 = 24

Page 36 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

4 a. Implementing program using Functions (Largest number in a list, area of shape

#Largest number in a list


def mymax(list1):
max=list1[0]
for x in list1:
if x>max:
max=x
return max
list1=[10,20,30,40,55,99]
print("largest element is:",mymax(list1))

#Area of shape
def calculate_area(name):
if name=="rectangle": l=int(input("enter
rectangle length:"))
b=int(input("enter rectangle breadth:"))
rect_area=l*b
print(f"the area of rectangle is {rect_area}")
elif name=="square":
s=int(input("enter square side length:"))
sqt_area=s*s
print(f"the area of square is {sqt_area}")
elif name=="triangle":
h=int(input("enter triangle height length:"))
b=int(input("enter triangle breadth length:"))
tri_area=0.5*h*b
print(f"the area of triangle is {tri_area}")
elif name=="circle":
r=int(input("enter circle radius length:"))
pi=3.14
circ_area=pi*r*r
print(f"the area of circle is {circ_area}")
elif name=="parallelogram":
b=int(input("enter parallelogram base length:"))
h=int(input("enter parallelogram height length:"))

Page 37 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

para_area=b*h
print(f"the area of parallelogram is {para_area}")
else:
print("sorry! this shape is not available.") if
__name ==" main ":
print("calculate shape area")
shape_name=input("enter the name of shape whose area you want to find:")
calculate_area(shape_name)

OUTPUT
calculate shape area
enter the name of shape whose area you want to find:triangle
enter triangle height length:5
enter triangle breadth length:3 the
area of triangle is 7.5

Page 38 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

4b. implementing a real-time/technical application using Exception handling (Divide by Zero


error, Voter’s age validity, student mark range validation)
# divide by Zero error
a=int(input("enter a:"))
b=int(input("enter b:")) try:
c=((a+b)/(a-b)) if
a==b:
raise ZeroDivisionError
except ZeroDivisionError:
print("a/b result is 0")
else:
print(c)

#2.Voter's Age Validity

print("Voter's Age Validity")


def voting():

try:

age=int(input("Enter your age")) if


age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:

print("age must be a valid number")

voting()

# student mark range validation name=input("enter


the student name:") regno=input("enter the student
register number:") try:
mark1=int(input("enter the mark1:"))

Page 39 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

mark2=int(input("enter the mark2:"))


if(0<=mark1<=100)and(0<=mark2<=100):
print("marks are in the range")
else:
raise ValueError("marks are not in range")
except ValueError as err:
print(err) finally:
print("thankyou,you have successfully checked")

OUTPUT

enter a:5
enter b:5
a/b result is 0 Voter's
Age Validity Enter
your age32 Eligible
to vote
enter the student name:jerry
enter the student register number:sw21aim001
enter the mark1:70
enter the mark2:30
marks are in the range
thankyou,you have successfully checked

Page 40 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
5.Using Regular expressions, develop a Python program to

a. Identify a word with a sequence of one upper case letter followed by lower case letters.

import re
def search(ip_str):
re_exp = '[A-Z]+[a-z]+$'
if re.search(re_exp, ip_str):
print('Yes, the required sequence exists!')
else:
print('No, the required sequence does not exists!')
ip_str = input("Enter the string: ")
search(ip_str)
output:
Enter the string: AbvfjNDb
Yes, the required sequence exists!
Enter the string: abbb
No, the required sequence does not exists!

Page 41 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

5.b. Find all the patterns of “1(0+)1” in a given string.

import re
str = '11001001'
match = re.search('1(0+)1', str)
# If-statement after search() tests if it succeeded
if match:
print('found') ## 'found word:cat'
else:
print('did not find')
def patternCount(str):
# Variable to store the last character
last = str[0]
i = 1; counter = 0
while (i < len(str)):

# We found 0 and last character was '1',


# state change
if (str[i] == '0' and last == '1'):
while (str[i] == '0'):
i += 1
# After the stream of 0's, we got a '1',
# counter incremented
if (str[i] == '1'):
counter += 1

# Last character stored


last = str[i]
i += 1
return counter
ans = patternCount(str)
print (ans)
OUTPUT:
Found

Page 42 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
6a. SET1 and SET2 are two sets that contain unique integers. SET3 is to be created by taking
the union or intersection of SET1 and SET2 using the user defined function Operation ().
Perform either union or intersection by reading the choice from the user. Do not use built-in
function union () and intersection () and also the operators “|” and “&”.
set1=[1,2,3,4,5,6]
set2=[1,2,3,5,7,9,10]
set3=[]
def operation(choice): if
choice=="union":
for row in set2:
set1.append(row)
for col in set1:
set3.append(col)
elif choice=="intersection": for
row in set1:
if row in set2:
set3.append(row)
for col in set2:
if col in set1:
set3.append(col)
return set(set3)
print(operation("intersection"))

OUTPUT
#intersection
{1, 2, 3, 5}
#union
{1, 2, 3, 4, 5, 6, 7, 9, 10}

Page 43 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

6b. The Dictionary “DICT1” contains N Elements and each element in the dictionary has the
operator as the KEY and operands as VALUES. Perform the operations on operands using
operators stored as keys. Display the results of all operations.
dict1={'stdno':'532','stuname':'naveen','stuage':'21','stucity':'hyderabad'}
print("\n dictionary is:",dict1)
print("\n student name is:",dict1['stuname'])
print("\n student city is:",dict1['stucity'])
print("\n all key in dictionary")
for x in dict1:
print(x)
print("\n all key in dictionary")
for x in dict1:
print(dict1[x])
dict1["phno"]=6884762859
print("updated dictionary is:",dict1)
dict1["stuname"]="jerry" print("updated
dictionary is:",dict1) dict1.pop("stuage")
print("updated dictionary is:",dict1)
print("length of dictionary is:",len(dict1))
dict2=dict1.copy()
print("\n new dictionary is:",dict2)
dict1.clear()
print("updated dictionary is:",dict1)

Page 44 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

OUTPUT
dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad'}

student name is: naveen

student city is: hyderabad

all key in dictionary


stdno
stuname
stuage
stucity

all key in dictionary


532
naveen 21
hyderabad
updated dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859} length of
dictionary is: 4

new dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859} updated
dictionary is: {}

Page 45 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

7. Implementing program using Strings. (Reverse, palindrome, character count, replacing


characters)

''' REVERSE A STRING '''

def reversed_string(text): if

len(text) == 1:

return text

return reversed_string(text[1:]) + text[:1]

print(reversed_string("Python Programming!")) '''


PALINDROME '''

def isPalindrome(s):

return s == s[::-1]

s = input("enter any string :")


ans = isPalindrome(s)
if ans:

print(s,"Yes it's a palindrome")


else:

print(s,"No it's not a palindrome")


'''CHARACTER COUNT'''

def count_chars(txt): result


=0
for char in txt:

result += 1 # same as result = result + 1


return result
text=input("enter any string")

print("no.of characters in a string",count_chars(text))


'''REPLACING CHARACTERS'''

string = "python programming language is powerful"


print(string.replace("p", "P",1))
print(string.replace("p", "P"))
OUTPUT

Page 46 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

!gnimmargorP nohtyP enter


any string :MADAM
MADAM Yes it's a palindrome
enter any string :MAA
MAA No it's not a palindrome
enter any string MANGO no.of

characters in a string 6
Python programming language is powerful
Python Programming language is Powerful

Page 47 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

8. a. Develop a program to print the 10 most frequently appearing words in a text file. [Hint: Use
a dictionary with distinct words and their frequency of occurrences. Sort the dictionary in the
reverse order of frequency and display the dictionary slice of the first 10 items]

from collections import Counter

import re

text = """The Python Software Foundation (PSF) is a 501(c)(3) non-profit corporation

that holds the intellectual property rights behind

the Python programming language. We manage the open source licensing for

Python version 2.1 and later and own and protect the trademarks associated

with Python. We also run the North American PyCon conference annually,

support other Python conferences around the world, and

fund Python related development with our grants program and by funding special

projects."""

words = re.findall('\w+',text)

print(Counter(words).most_common(10))

Output:

[('Python', 6), ('the', 6), ('and', 5), ('We', 2), ('with', 2), ('The', 1), ('Software', 1), ('Foundation', 1),
('PSF', 1), ('is', 1)]

Page 48 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

8b. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file.

def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close() words.sort()
outfile = open("result.txt", "w") for i
in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")

input file: sample.txt

ZEBRA AND OX ARE GOOD FRIENDS. DOGS ARE VERY LOYAL AND FAITHFUL.

Output file: output.txt

AND AND ARE ARE DOGS FAITHFUL. FRIENDS. GOOD LOYAL OX VERY ZEBRA

Page 49 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

8c. Develop a program to backing up a given Folder (Folder in a current working directory) into a
ZIP File by using relevant modules and suitable methods.
import zipfile, os

def backupToZip(folder):

# Backup the entire contents of "folder" into a zip file.

folder = os.path.abspath(folder) # make sure folder is absolute

# Figure out the filename this code should used based on what files already exist.

number = 1

while True:

zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip' if

not os.path.exists(zipFilename):

break

number = number + 1 #

Create the zip file.

print('Creating %s...' % (zipFilename)) backupZip

= zipfile.ZipFile(zipFilename, 'w')

# Walk the entire folder tree and compress the files in each folder. for

foldername, subfolders, filenames in os.walk(folder):

print('Adding files in %s...' % (foldername)) #

Add the current folder to the ZIP file.

backupZip.write(foldername)

# Add all the files in this folder to the ZIP file.

for filename in filenames:

if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):

continue # don't backup the backup ZIP files

backupZip.write(os.path.join(foldername, filename))

backupZip.clos-e()

print('Done.')

backupToZip('C:\\delicious')

Page 50 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

Output:

Creating delicious_1.zip... Do

Page 51 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

9. Develop a program that uses class Students which prompts the User to enter marks in three
subjects and calculate total marks,Percentage and display the score card details. [Hint: Use list to
store the marks in three subjects and total marks. Use_init() method to initialize name, USN and
the lists to store marks and total, Use getMarks() method to read marks into the list, and
display() method to display the score card details.]

class Student:

marks = []

def __init (self,name,rn):

self.name = name
self.rn = rn

def getMarks(self, m1, m2, m3):


Self.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)

def displayData(self):

print (&quot;Name is: &quot;, self.name)


print (&quot;USN is: &quot;, self.rn)

print (&quot;Marks in subject 1: &quot;, Student.marks[0])


print (&quot;Marks in subject 2: &quot;, Student.marks[1])

print (&quot;Marks in subject 3: &quot;, Student.marks[2])


print (&quot;Marks are: &quot;, Student.marks)

print (&quot;Total Marks are: &quot;, self.total())

print (&quot;Average Marks are: &quot;, self.average())

def total(self):

return (Student.marks[0] + Student.marks[1] +Student.marks[2]) def


average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

Page 52 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

name = input(&quot;Enter the name: &quot;) r =

input(&quot;Enter the USN: &quot;)


m1 = int (input(&quot;Enter the marks in the first subject: &quot;)) m2 =
int (input(&quot;Enter the marks in the second subject: &quot;)) m3 = int
(input(&quot;Enter the marks in the third subject: &quot;))

s1 = Student(name,r)
s1.getMarks(m1, m2, m3)
s1.displayData()

OUTPUT

Enter the name: AKSHARA


Enter the USN: SW22AIM001
Enter the marks in the first subject: 99
Enter the marks in the second subject: 89
Enter the marks in the third subject: 88

Name is: AKSHARA


USN is: SW22AIM001

Marks in subject 1: 99

Marks in subject 2: 89

Marks in subject 3: 88

Marks are: [99, 89, 88]

Total Marks are: 276


Average Marks are: 92.0

Page 53 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

#10. '''Implementing program using modules and python Standard Library (pandas)'''

import pandas as pd df
= pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],
}
)
print(df) print(df["Age"])
ages = pd.Series([22, 35, 58], name= "age")
print(ages)
df["Age"].max()
print(ages.max())
print(df.describe())

Output
Name Age Sex
0 Braund, Mr. Owen Harris 22 male 1
Allen, Mr. William Henry 35 male 2
Bonnell, Miss. Elizabeth 58 female 0
22
1 35
2 58
Name: Age, dtype: int64 0
22
1 35
2 58
Name: age, dtype: int64 58
Age count
3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000

Page 54 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

#10.b. Implementing program using modules and python Standard Library (Numpy)
import numpy as np a =
np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1]) np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape a
= np.arange(6) print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
Output
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]

Page 55 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

#10. c. Implementing program using modules and python Standard


Library(Matplotlib)
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b'] plt.pie(slices,labels=activities,
colors=cols, startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Pie Plot') plt.show()

Output

Page 56 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

#10. d. Implementing program using modules and python StandardLibrary(Scipy)


import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(5, 20) y
= np.exp(x/3.0)
f = interpolate.interp1d(x, y) x1
= np.arange(6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()

Output

Page 57 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
PYTHON LAB VIVA QUESTIONS

1.What is Python?
Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose
language, it can be used to build almost any type of application with the right tools/libraries.

2. What are the applications of Python?


Web and Internet Development Games Scientific and computational applications Language development
Image processing and graphic design applications

3.What is the difference between a list and a tuple?


List :Lists are enclosed with in square []Lists are mutable, that is their elements and size can be changed.
Lists are slower than tuples .Example: [‘A’, 1, ‘i’]Tuple: Tuples are enclosed in parentheses ()Tuples are
immutable i.e cannot be edited. Tuples are faster than lists. Tuples must be used when the order of the
elements of a sequence matters. Example: (‘Twenty’, 20, ‘XX’)

4.Define Lambda function?


A lambda function is a small anonymous function. A lambda function can takes any of arguments but can
have only one expression..eg: x= lambda a:a+10 print(x)

5.What is the difference between del(), clear(), remove(), and pop()?


del(): deletes the with respect to the position of the value. It does not return which value is deleted. It also
changes the index towards the right by decreasing one value. It can also be used to delete the entire
data structure.clear(): clears the list.remove(): it deletes with respect to the value hence can be used if
you know which particular value to delete.pop(): by default removes the last element and also returns back
which value is deleted. It is used extensively when we would want to create referencing. In sense,we can
store this deleted return value in a variable and use in future

6. What is the difference between pass, continue and break?

Page 58 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
Pass: It is used when you need some block of code syntactically, but you want to skip its execution. This
is basically a null operation. Nothing happens when this is executed. Continue: It allows to skip some part
of a loop when some specific condition is met,and the control is transferred to the beginning of the loop.
The loop does not terminate but continues with the next iteration .Break: It allows the loop to terminate
when some condition is met, and the control ofthe program flows to the statement immediately after the
body of the loop. If the break statement is inside a nested loop (the loop inside another loop), then the
break statement will terminate the innermost loop.

7.What is Regex? List some of the important Regex functions in Python.


Regular Expression or RegEx is a sequence of characters that are used to create search patterns. In Python,
the following RegEx functions are mostly used:match(): it checks for a match only at the beginning of the
string.search(): it locates a substring matching the RegEx pattern anywhere in the stringsub(): searches for
the pattern and replaces with a new valuesplit(): it is used to split the text by the given RegEx
pattern.findall(): it is used to find all the sub-strings matching the RegEx pattern

8. What is a class and object?


A class is a user-defined prototype which basically is a blueprint that defines thenature of a future object.
An object is an instance of the class. Therefore, classes can construct instances of objects. This is known
as instantiation.

9. What is a docstring?
Python document strings (or docstrings) describe what the function does. These are within the triple
quotes. Also, it can be accessed using two ways: one via _doc_attribute and via by adding a period (.) next
to the function name and pressing tab. Itis a way to associate documentation with Python modules,
functions, classes, and methods

10. How do map, reduce and filter functions work


?Map function applies the given function to all the iterable and returns a new modifiedlist. It applies
the same function to each element of a sequence .Reduce function applies the same operation to items of a
sequence. It uses the result of operations as the first param of the next operation. It returns an item and
nota list.Filter function filters an item out of a sequence. It is used to filter the given iterable(list, sets,

Page 59 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
tuple) with the help of another function passed as an argument to test all the elements to be true or false.
Its output is a filtered list.
11.What are local variables and global variables in Python?

Global Variables: Variables declared outside a function or in a global space are called global variables.
These variables can be accessed by any function in the program.

Local Variables: Any variable declared inside a function is known as a local variable. This variable is
present in the local space and not in the global space.

12.When to use a tuple vs list vs dictionary in Python?

Use a tuple to store a sequence of items that will not change.

Use a list to store a sequence of items that may change.

Use a dictionary when you want to associate pairs of two items.

NUMPY:

Page 60 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
1. What is NumPy? Why should we use it?
NumPy (also called Numerical Python) is a highly flexible, optimized, open -source package
meant for array processing. I t p r o v i d e s t o o l s f o r d e l i v e r i n g h i g h -
e n d p e r f o r m a n c e w h i l e d e a l i n g w i t h N - dimensional powerful array objects.It is also
beneficial for performing scientific computations, mathematical, and logical operations, sorting
operations, I/O functions, basic statistical and linear algebra -based operations along with
random simulation and broadcasting functionalities.

2. Where is NumPy used?


NumPy is an open source numerical Python library. NumPy contains a multi-dimentional array and matrix
data structures. It can be utilised to perform a number of mathematical operations on arrays such as
trigonometric, statistical and algebraicroutines. NumPy is an extension of Numeric and Numarray.

3. Why is NumPy preferred over Matlab, Idl ?


Powerful functions for performing complex mathematical operations on multi-dimensional matrices and
arrays
The operations on ndarrays of NumPy are approximately up to 50% faster than thelist in python. ·Provides
indexing syntax to access portions of data easily in a large array.· Provides built-in functions ·It takes only
a few lines of code to achieve complex computations using NumPy

4. How are NumPy arrays better than Python’s lists?


Python lists support storing heterogeneous data types whereas NumPy arrays can store datatypes of one
nature itself. NumPy provides extra functional capabilities that make operating on its arrays easier which
makes NumPy array advantageous in comparison to Python lists as those functions cannot be operated on
heterogeneous data

.5. What are the types of sorting in numpy with syntax?


sorting types:-sort - np.sort()argsort - np.argsort()-returns index sorting valuelexsort-np.lexsort(a,b)-two
array as given as argument and it returns indcesthat describes the sort order by multiple columns

6.How is np.mean() different from np.average() in NumPy?

Page 61 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
np.mean() method calculates the arithmetic mean and provides additional optionsfor input and results.
For example, it has the option to specify what data types haveto be taken, where the result has to be placed
etc.· np.average() computes the weighted average if the weights parameter is specified.In the case of
weighted average, instead of considering that each data point iscontributing equally to the final average,
it considers that some data points have more weight age than the others (unequal contribution)

7.What are ndarrays in NumPy?


When the size of ndarrays is changed, it results in a new array and the original array is deleted.
The ndarrays are bound to store homogeneous data.· They provide functions to perform advanced
mathematical operations in an efficient manner

8.What is numpy structured array?


Numpy's Structured Array is similar to Struct in C. It is used for grouping data ofdifferent types and
sizes. Structure array uses data containers called fields. Each data field can contain data of any type and
size.hat is structured array?

9.What is the difference between ndarray and array in NumPy?


Using array(), zeros() or empty() methods: Arrays should be constructed usingarray, zeros or empty
(refer to the See Also section below). The parameters are given here refer to a low-level method
(ndarray(…)) for instantiating an array
.2. From ndarray class directly: There are two modes of creating an array using __new__: If buffer is
None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface,
then all keywords are interpreted.

10.what is Vectorization in NumPy


Answer:Vectorization takes one elemental operation and applies to all the elements in thatarray for you.
Underneath, the implementatiosn are in C, hence providing substantialspeed gains. NumPy already has a
large number of operations vectorized, for eg: allarithmetic operators, logical operators, etc. Numpy also
provides a way for you tovectorize your function.
PANDAS:

Page 62 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
1)What is pandas in python?
Pandas is an open source python package that is most widely used for datascience/data analysis and
machine learning tasks. It is built on top of another package named Numpy which provides support
for multi-dimensional arrays.

2)Mention the different types of Data Structures in Pandas?


1.Series2.DataFrames
A Series is a one-dimensional data structure in pandas, whereas the
DataFrame is the two-dimensional data structure in pandas.

3)Define Reindexing in Pandas?


R e i n d e x i n g i s u s e d t o c h a n g e t h e i n d e x o f t h e r o w s a n d c o l u m n s o f t h e DataFrame.
We can reindex the single or multiple rows by using the reindex() method. Default values in the new index
are assigned NaN if it is not present in the DataFrame.
D a t a F r a m e . r e i n d e x ( l a b e l s = N o n e , i n d e x = N o n e , c o l u m n s = N o n e , ax
i s = N o n e , m e t h o d = N o n e , c o p y = T r u e , l e v e l = N o n e , f i l l _ v a l u e = n a n , limit=None, tole
rance=None)

4)List out the features of Pandas Library?


The pandas library has a number of features, some of which are shown here.
Memory Efficient
Time Series
Reshaping
Data Alignment
Merge and join

5)How to create empty dataFrame in Pandas?


To make a Pandas data frame that is fully empty, perform the following: import pandas as pdMyEmptydf
()= pd.DataFrame This will result in a data frame that has no columns or rows. We do the following
to construct an empty dataframe with three empty columns(columns A, B, and C): df=
pd.DataFrame(columns=['A', 'B', 'C'])

Page 63 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __

6)What type of inputs are accepted by pandas?


Like Series, DataFrame accepts many different kinds of input:
Dict of 1D ndarrays, lists, dicts, or Series.
2-D numpy. ndarray.
Structured or recorded ndarray.
A Series.
Another DataFrame.

8)What is groupby() function in pandas?


I n P a n d a s , g r o u p b y ( ) f u n c t i o n a l l o w s t h e p r o g r a m m e r s t o r e a r r a n g e data by using
them on real-world sets. The primary task of the function is to split the data into various
groups.

9 ) D e f i n e i l o c ( ) a n d l o c ( ) i n p a n d a s ? The iloc() function


is an indexed-based selecting method which means
thatw e h a v e t o p a s s a n i n t e g e r i n d e x i n t h e m e t h o d t o s e l e c t a s p e
c i f i c row/column. This method does not include the last element of the
r a n g e passed in it unlike loc(). Iloc() does not accept the Boolean data unlike loc().

The loc() function


is label based data selecting method which means that wehave to pass the name of the row or
column which we want to select. This method includes the last element of the range passed in it,
unlike iloc(). loc()can accept the Boolean data unlike iloc().

10)How to iterate over a Pandas DataFrame?


y o u c a n i t e r a t e o v e r t h e r o w s o f t h e D a t a F r a m e b y u s i n g f o r l o o p i n comb
ination with an iterrows() call on the DataFrame.import pandas as pd import numpy as
np df = pd.DataFrame([{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]) for index, row
in df.iterrows(): print(row['c1'], row['c2'])Output:10 100 11 110 12 120
MATPLOTLIB:

Page 64 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
1.what are magic functions in matplotlib?
ans:%matplotlib notebook & %matplotlib inline

2. What is a Pairplot
Ans:A Pair plot shows the relationships for a pair of columns of the data.It creates a matrix of axes
where the diagonals show the distribution of each variablewith itself.

3.what is use of markers in matplotplib?


ans:it is module which can be used in both scatter and plot.It consist of facecolor,edgecolor,edgewidth
etc..(circle,point,pixel,triangle-up,triangle-down etc..,)

4.what is the module to import 3d matplotlib?


ans:from mpl_toolkits import mplot3d

5.what is legend and use of it?


ans:legend is the element to describe the graph andthe location can be given to place the legend
ex:upperleft,upper roght,lowerleft,lower right

6.what is cmap?
ans:cmap stands for colormap and it's a colormap instance or registered colormapname

7.what is the use of magic function?


ans:Magic methods are most frequently used to define overloaded behaviours ofpredefined operators in
Python

8.what is the use of figure function?


ans:The figure() function in pyplot module of matplotlib library is used to create anew figure

9.what are the arguments to be given in the linspace function?


ans: (range,collection of points).
10.what is the property of alpha?

Page 65 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
ans:it used for color value transparancy.

11.what are the methods of visulaiztion tools in maytplotlib?


ans:plot(linear polt),scatt
erplot,contour polt,histogram,etc..

Page 66 of 66
DEPT. OF CSE,FETW ,SUK

You might also like