LAB 4 Sem
LAB 4 Sem
ALGORITHMS Laboratory
(22CSL46)
Manual
INDEX
PART-A
PART – B
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.
# 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();
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:
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++)
{
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:
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))
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:
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;
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++) {
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");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}
OUTPUT:
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);
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;
}
}
}
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;
}
OUTPUT:
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);
}
OUTPUT:
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);
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]);
}
}
OUTPUT:
OUTPUT:
#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;
sumofsub ( m , k + 1 , r - s[k] ) ;
}
}
OUTPUT:
#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
completed[i]=0;
}
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
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;
if(min!=999)
cost+=kmin;
return nc;
}
int main()
{
takeInput();
return 0;
}
OUTPUT:
<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>
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. ?>
<?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;
?>.
<?php
// the variable
echo $myDate;
?>
<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>
<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>
<?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;
}
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
</body>
</html>
Database Management System Lab(21CSL48)
Table Creation
3 CD Sep-2016 PEARSON
4 ALGORITHMS Sep-2015 MIT
5 OS May-2016 PEARSON
AUTHOR_NAME BOOK_ID
NAVATHE 1
NAVATHE 2
ULLMAN 3
CHARLES 4
GALVIN 5
CARDNO
101
102
103
104
105
Queries:
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in
each Programme, etc.
3 CD PEARSON ULLMAN 7 14
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.
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.
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)
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);
5. Demonstrate the DELETE operation by removing salesman with id 1000.All his orders must also be
deleted.
Output:
Factorial of 6 is 720
Procedure successfully completed
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 Ticket_no
1 Sita 32
2 Ram 25
3 John 56
4 Mary 45
dbms_output.put_line('updcheck called');
END;
Output:
Trigger Created
Output:
Package Created
DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
Output:
Salary:2500
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
Page 1 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
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.
✓ 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
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.
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
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
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
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
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
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
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
PO9: Individual and Team Work: Function effectively as an individual and as a member or leader to
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
PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to engage in
Page 4 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
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
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
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
Page 8 of
DEPT. OF CSE,FETW ,SUK 66
PYTHON LAB MANUAL(22CSL48) 2023-2024
1. INTRODUCTION TO PYTHON
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
• 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.
• 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 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 3:Download.
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 __
Page 15 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
BASICS OF PYTHON
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:
Page 18 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
type from the input function. For example:
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
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 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 __
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==
==case -2==
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
else:
print("Not Senior")
OUTPUT
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)):
m = statistics.mean ( a )
v = statistics.variance ( a ) st
= statistics.stdev ( a ) print(
"Mean: ",m)
print( "Variance: ",v)
OUTPUT
number : 4
number : 5
Mean: 4
Variance: 1
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))
OUTPUT
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.'''
OUTPUT
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
import time;
ltime=time.localtime();
OUTPUT
Page 31 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
. 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
OUTPUT
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: "))
largest = num1
largest = num2
else:
largest = num3
OUTPUT
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
count = 0
nth = n1 + n2
# update values n1
= n2
n2 = nth
count += 1
OUTPUT
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)
for i in range(1,num+1):
fact=fact*i
return 0
if k == 0 or k == n:
return 1
# Recursive Call
n=5
k=2
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 __
#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 __
try:
voting()
Page 39 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
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 __
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)):
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'}
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 __
def reversed_string(text): if
len(text) == 1:
return text
def isPalindrome(s):
return s == s[::-1]
Page 46 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
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]
import re
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,
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")
ZEBRA AND OX ARE GOOD FRIENDS. DOGS ARE VERY LOYAL AND FAITHFUL.
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):
# Figure out the filename this code should used based on what files already exist.
number = 1
while True:
not os.path.exists(zipFilename):
break
number = number + 1 #
= zipfile.ZipFile(zipFilename, 'w')
# Walk the entire folder tree and compress the files in each folder. for
backupZip.write(foldername)
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 = []
self.name = name
self.rn = rn
def displayData(self):
def total(self):
Page 52 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
s1 = Student(name,r)
s1.getMarks(m1, m2, m3)
s1.displayData()
OUTPUT
Marks in subject 1: 99
Marks in subject 2: 89
Marks in subject 3: 88
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 __
Output
Page 56 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
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.
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.
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
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.
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.
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)
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.
Page 63 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
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.
6.what is cmap?
ans:cmap stands for colormap and it's a colormap instance or registered colormapname
Page 65 of 66
DEPT. OF CSE,FETW ,SUK
PYTHON LAB MANUAL(22CSL48) 2023-2024 __
ans:it used for color value transparancy.
Page 66 of 66
DEPT. OF CSE,FETW ,SUK