You are on page 1of 24

16.

STACK IMPLEMENTATION
AIM: To implement the stack operation using a list data structure
ALGORITHM:
Step 1: Start the program execution Step 2: Read the value of choice
Step 3: Check if choice==1, then call the function view( ) – To view the
element in stack , else go to step 4
Step 4: Check if choice==2, then call the function push( ) – To insert an
element into stack, else go to step 5
Step 5: Check if choice==3, then call the function pop( ) – To delete an
element from stack, else go to step 6
Step 6: Check if choice==4, then call the function peek( ) – To display top
element of stack, else go to step 7
Step 7: Print “Wrong choice”
Step 8: Stop the program execution

Expected Input:
Push (Choice:2) Data →11,22,33,44,55
Peek ( Choice : 4)
Pop (Choice: 3)
View (Choice: 1)

Expected Output:

Data Pushed
Peeked: 55
Popped: 55
Traversed:
44
33
22
11
Code:

stack=[ ]

def c_stkMT():
if len(stack) == 0:
return True
else:
return False

def view( ):
if c_stkMT():
print("Stack empty.. ")
else:
for x in range(len(stack)-1,-1,-1):
print(stack[x])
def push( ):
item=int(input("Enter integer value"))
stack.append(item)

def pop( ):
if c_stkMT():
print("Stack empty")
else:
item=stack.pop(-1)
print("Deleted element:",item)

def peek( ):
if c_stkMT():
print("Stack is empty.. ")
else:
item=stack[-1]
print("Peeked element:",item)

print("Stack operation")
print("************")
print("1.View")
print("2.Push")
print("3.Pop")
print("4.Peek")
print("5.Quit")
while True:
choice=int(input("Enter your choice: "))
if choice ==1:
view( )
elif choice == 2:
push( )
elif choice == 3:
pop( )
elif choice == 4:
peek( )
elif choice == 5:
break
else:
print("Wrong choice")

RESULT: Thus the stack program executed successfully.

OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITH THE BOX)
Stack operation
************
1.View
2.Push
3.Pop
4.Peek
5.Quit
Enter your choice: 2
Enter integer value11

Enter your choice: 2


Enter integer value22

Enter your choice: 2


Enter integer value33

Enter your choice: 2


Enter integer value44

Enter your choice: 2


Enter integer value55

Enter your choice: 1


55
44
33
22
11
Enter your choice: 4
Peeked element: 55

Enter your choice: 3


Deleted element: 55

Enter your choice: 1


44
33
22
11
Enter your choice: 5
17. Stack Operations (Extracting data from Dictionary)
Aim:
To write a python program on stack implementation to
a) Push the keys (book_name) of the dictionary into a stack, where the corresponding
value (rating) is more than 8.
b) Traverse the content of the stack
c) Pop and display the content of the stack.
Algorithm:
Step 1: Start the program execution
Step 2: Read the value of choice
Step 3: Check if choice==1, then call the function PushBooks( ) – To insert the book
names into stack and goto step2, else go to step 4
Step 4: Check if choice==2, then call the function ViewBooks( ) – To view the
elements of the stack, else go to step 5
Step 5: Check if choice==3, then call the function PopBooks( ) – To delete an element
from stack, and goto step2
Step 6: Check if choice == 4 then goto step 8 else goto step 7
Step 7: Print “Wrong choice” and goto step2
Step 8: Stop the program execution

Expected input
B = {"AI 2041: Ten Visions for Our Future":7.9,
"Beginners: The Transformative Joy of Lifelong Learning":8.5,
"Bravey: Chasing Dreams, Befriending Pain, and Other Big Ideas":9,
"Chatter: The Voice in Our Head, Why It Matters, and How to Harness It":8.2,
"The Code Breaker: Jennifer Doudna, Gene Editing, and the Future of the Human
Race":7.5 }
Expected Output
Beginners: The Transformative Joy of Lifelong Learning,
Bravey: Chasing Dreams, Befriending Pain, and Other Big Ideas,
Chatter: The Voice in Our Head, Why It Matters, and How to Harness It

Code:
libBookDic = {"AI 2041: Ten Visions for Our Future":7.9,
"Beginners: The Transformative Joy of Lifelong Learning":8.5,
"Bravey: Chasing Dreams, Befriending Pain, and Other Big Ideas":9,
"Chatter: The Voice in Our Head, Why It Matters, and How to Harness It":8.2,
"The Code Breaker: Jennifer Doudna, Gene Editing, and the Future of the
Human Race":7.5}

stkLst = []
top = -1
def isEmpty(top):
if top==-1:
return True
else:
return False

def PushBooks(bookDic):
global stkLst, top
for i in libBookDic:
if libBookDic[i] > 8:
stkLst.append(i)
top+=1
print("Elements are pushed")

def PopBooks():
global stkLst, top
if isEmpty(top):
print("Stack Empty")
else:
print("Poped Book is ", stkLst.pop())
top-=1

def ViewBook():
global stkLst, top
if isEmpty(top):
print("Stack Empty")
else:
print ("Top element -->",end=' ')
for ind in range(top,-1,-1):
print(stkLst[ind])

while True:
print("Book Stack Operation")
print("1. Add Books \n 2. View Books in stack \n 3. Remove a book \n 4. Exit")
ch = int(input("Enter your choice "))
if ch == 1:
PushBooks(libBookDic)
libBookDic.clear()
elif ch == 2:
ViewBook()
elif ch == 3:
PopBooks()
elif ch == 4:
break
else:
print("Enter a valid choice...")

RESULT: Thus the stack program executed successfully.


OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITH THE BOX)

Book Stack Operation


1. Add Books
2. View Books in stack
3. Remove a book
4. Exit
Enter your choice 1
Elements are pushed

Enter your choice 2


Top element --> Chatter: The Voice in Our Head, Why It Matters, and
How to Harness It
Bravey: Chasing Dreams, Befriending Pain, and Other Big Ideas
Beginners: The Transformative Joy of Lifelong Learning

Enter your choice 3


Poped Book is Chatter: The Voice in Our Head, Why It Matters, and
How to Harness It

Enter your choice 2


Top element --> Bravey: Chasing Dreams, Befriending Pain, and
Other Big Ideas
Beginners: The Transformative Joy of Lifelong Learning

Enter your choice 4


18. SQL Query (DDL Statements)

Aim: To create a database called Sports and to perform the following:

a) Create a table “TEAM” with following considerations:


a. It should have a column TeamID for storing an integer value between 1
and 9, which refers to the unique identification of a team.
b. Each TeamID should have its associated name (Team Titan, Team
Rockers, Team Magnet and Team Hurricane), which should be a string of
length not less than 10 characters.
c. Using table level constraint, make TeamID as the primary key.
b) Show the structure of the table TEAM using a SQL statement.
c) Insert four rows in TEAM table:
a. Row 1: (1, Tehlka)
b. Row 2: (2, Toofan)
c. Row 3: (3, Aandhi)
d. Row 3: (4, Shailab)
d) Show the contents of the table TEAM using a DML statement.
e) Create another table MATCH_DETAILS and insert data as shown below. Choose
appropriate data types and constraints for each attribute.

Result:
The database and the tables were created.
Output: (Write on the left side; parallel to aim)
create database sports;

a) Creating table with the given specification


CREATE TABLE Team
(teamid int,
teamname varchar(10), PRIMARY KEY(teamid));
b) desc team;

c) Inserting data:
insert into team
values(1,'Tehlka'),
values(2,’Toofan'),
values(1,’Aandhi’),
values(1,’Shailab’);
d) Show the content of table - team:
select * from team;

e) Creating another table:


create table match_details
(matchid varchar(2) primary key,
matchdate date,
firstteamid int references team(teamid),
secondteamid int references team(teamid),
firstteamscore int,
secondteamscore int);
19. SQL Query - DML Statements)

Aim: To open the database sports and do the following:

a) Insert the data as given above and display all records

b) Display matchid, teamname and secondteamscore between 100 to 160.

c) Display matchid, teamnames along with matchdates.

d) Display unique team names

e) Display matchid and matchdate played by Anadhi and Shailab.

Result:

The data were inserted and details were displayed

a) Insert the records:


Insert into match_details values(‘M1’,’2021-12-20’,1,2,107,93);
Insert into match_details values(‘M2’,’2021-12-21’,3,4,156,158);
Insert into match_details values(‘M3’,’2021-12-22’,1,3,86,81);
Insert into match_details values(‘M4’,’2021-12-23’,2,4,65,67);
Insert into match_details values(‘M5’,’2021-12-24’,1,4,52,88);
Insert into match_details values(‘M6’,’2021-12-25’,2,2,97,68);

b) Select matched, teamname, secondteamscore


from match_details, team
where match_details.secondteamid = team.teamid and
match_details.secondteamscore between 100 and 160;

c) select matchid, teamname, firstteamid, secondteamid, matchdate


from match_details, team
where match_details.firstteamid = team.teamid;

d) select distinct(teamname)
from match_details, team
where match_details.firstteamid = team.teamid;

e) select matchid,matchdate from match_details, team


where match_details.firstteamid = team.teamid and
team.teamname in ('Aandhi','Shailab');

20. ITEM AND TRADERS (Group by Clause)

AIM: To create two tables for item and traders and execute the given commands using
SQL.

TABLE:ITEM
Code IName Qty Price Company TCode
1001 DIGITAL PAD 121 120 1100 XENTIA T01
0
1006 LED SCREEN 40 70 3800 SANTORA T02
0
1004 CAR GPS SYSTEM 50 2150 GEOKNOW T01
1003 DIGITAL CAMERA 12X 160 8000 DIGICLICK T02

1005 PEN DRIVE 32GB 600 1200 STOREHOME T03

TABLE:TRADERS

TCode TName City

T01 ELECTRONICS SALES MUMBAI

T03 BUSY STORE CORP DELHI

T02 DISP HOUSE INC CHENNAI

i) To display the details of all the items in ascending order of item names (i.e IName)
ii) To display item name and price of all those items, whose price is in the
range of 10000 and 22000 (both values inclusive)
iii) To display the number of items , which are traded by each trader. The
expected output of this query should be
T01 2
T02 2
T03 1
iv) To display the Price , item name(i.e IName) and quantity(i.e Qty) of those
items which have quantity more than 150.

v) To display the names of those traders, who are either from DELHI or
from MUMBAI.

Queries: (To create table and insert Data)

CREATE TABLE ITEM(

Code int , IName char(25) ,

Qty int ,

Price int ,

Company char(25),

TCode char(5));

INSERT INTO ITEM VALUES(1001,"DIGITAL PAD 121",120, 11000,"XENTIA", "T01");


INSERT INTO ITEM VALUES(1006,"LED SCREEN 40",70, 38000,"SANTORA", "T02");

(All other records will be inserted)

CREATE TABLE TRADERS(

TCode char(5) ,

TName char(25),

City char(20));

INSERT INTO TRADERS VALUES("T01","ELECTRONICS SALES","MUMBAI");

INSERT INTO TRADERS VALUES( "T03","BUSY STORE CORP","DELHI");

INSERT INTO TRADERS VALUES( "T02","DISP HOUSE INC","CHENNAI");

RESULT: Thus the given program executed successfully.


OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITHIN THE BOX)

i) select * from ITEM order by IName;

Code IName Qty Price Company TCode


1004 CAR GPS SYSTEM 50 2150 GEOKNOW T01
1003 DIGITAL CAMERA 12X 160 8000 DIGICLICK T02
1001 DIGITAL PAD 121 120 11000 XENTIA T01
1006 LED SCREEN 70 38000 SANTORA T02
1005 PEN DRIVE 32GB 600 1200 STORE HOME T03

ii) select IName , Price from ITEM where Price between 10000 and 22000;

IName Price
DIGITAL PAD 121 11000

iii) select TCode , count(*) from ITEM group by TCode;

Tcode Count(*)
T01 2
T02 2
T03 1

iv) select Price , IName , Qty from ITEM where Qty>150;

Price IName Qty


8000 DIGITAL CAMERA 12X 160
1200 PEN DRIVE 32GB 600

v) select TName from TRADERS where City in ("DELHI","MUMBAI");

TName
ELECTRONICS SALES
BUSY STORE CORP
21. DOCTOR AND SALARY (Aggregate Functions)

AIM: To create two tables for doctor and salary and execute the given
commands using SQL.

TABLE: DOCTOR

ID NAME DEPT SEX EXPERIENCE


101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15

TABLE: SALARY

ID BASIC ALLOWANCE CONSULTATION


101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300

i. Display NAME of all doctors who are in “MEDICINE” having more than 10
years experience from table DOCTOR
ii. Display the average salary of all doctors working in “ENT” department using the
tables DOCTOR and SALARY. (Salary=BASIC+ALLOWANCE)
iii. Display minimum ALLOWANCE of female doctors.

iv. Display DOCTOR.ID , NAME from the table DOCTOR and BASIC ,
ALLOWANCE from the table SALARY with their corresponding matching ID.
v. To display distinct department from the table doctor.

Queries: (To create table and insert Data)


CREATE TABLE DOCTOR(
ID int NOT NULL PRIMARY KEY,
NAME char(25) ,
DEPT char(25) ,
SEX char ,
EXPERIENCE int);

INSERT INTO DOCTOR VALUES(101,"John", "ENT","M",12);


INSERT INTO DOCTOR VALUES(104,"Smith", "ORTHOPEDIC","M",5);
(insert other records)

CREATE TABLE SALARY(


ID int,
BASIC int,
ALLOWANCE int,
CONSULTATION int);

INSERT INTO SALARY VLAUES(101, 12000,1000,300);


INSERT INTO SALARY VLAUES(104, 23000,2300,500);
(insert other records)

RESULT: Thus the given program executed successfully.


OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITHIN THE BOX)

i) select NAME from DOCTOR where DEPT=”MEDICINE” and EXPERIENCE >10;

NAME
Bill

ii) select avg(BASIC+ALLOWANCE) "avg salary" from DOCTOR , SALARY where DOCTOR.ID =
SALARY.ID and DEPT="ENT";

Avg salary
13000.00

iii) select min(ALLOWANCE) from SALARY, DOCTOR where SEX='F' and DOCTOR.ID =
SALARY.ID;

min(ALLOWANCE)
1700

iv) select DOCTOR.ID, NAME, BASIC ,ALLOWANCE from DOCTOR, SALARY where
DOCTOR.ID = SALARY.ID;

ID NAME BASIC ALLOWANCE


104 Smith 23000 2300

101 John 12000 1000

107 George 32000 4000

114 Lara 12000 5200

109 K George 42000 1700

105 Johnson 18900 1690

v) select distinct(DEPT) from DOCTOR;

DEPT
ENT
ORTHOPEDIC
CARDIOLOGY
SKIN
MEDICINE
22. INTEGRATE PYTHON WITH SQL - FETCHING RECORDS FROM TABLE

AIM: To integrate SQL with Python by importing the MySQL module and extracting data
from result set

PROGRAM:
import mysql.connector as sqltor
mycon=sqltor.connect(host=”localhost”, user=”root”, passwd=”root”,databse=”trinity”)
if mycon.is_connected( ) = = False:
print(“Error connecting to MySQL database”)
cursor=mycon.cursor( )
cursor.execute(“select * from student”)
data=cursor.fetchmany(3)
for row in data:
print(row)
mycon.close( )

RESULT: Thus the given program executed successfully.

OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITHIN THE BOX)

(1001, “Vinusha”, 50,70, 80 , “Namakkal”)

(1001, “Aswin”, 54,82, 85 , “Erode”)

(1001, “Bheem”, 90,73, 78 , “Salem”)


23. INTEGRATE PYTHON WITH SQL - COUNTING RECORDS FROM TABLE

AIM: To integrate SQL with Python by importing the MySQL module and extracting data
from result set

PROGRAM:

import mysql.connector as sqltor

mycon=sqltor.connect(host=”localhost”, user=”root”, passwd=”root”, databse=”trinity”)

if mycon.is_connected( ) = = False:
print(“Error connecting to MySQL database”)
cur=mycon.cursor( )
cur.execute(“select * from student”)
data=cur.fetchone( )
count=cur.rowcount
print(“Total number of rows retrieved from resultset :”, count)
data=cur.fetchone( )
count=cur.rowcount

print(“Total number of rows retrieved from resultset :”, count)

data=cur.fetchmany(3)
count = cur.rowcount

print(“Total number of rows retrieved from resultset :”, count)

RESULT: Thus the given program executed successfully.

OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITHIN THE BOX)
Total number of rows retrieved from resultset : 1

Total number of rows retrieved from resultset : 2

Total number of rows retrieved from resultset : 5


24. INTEGRATE SQL WITH PYTHON - SEARCHING A RECORD FROM TABLE

AIM: Integrate SQL with Python by importing the MySQL module to search an employee
using eno , if it is present in table display the record

PROGRAM:

import mysql.connector as mc

mycon=mc.connect(host='localhost',user='root',passwd='root1',data base='db12')

if mycon.is_connected( ):

print("Py->Sql connected")

eno=int(input("Enter num:"))

mcursor=mycon.cursor( )

mcursor.execute("select * from emp")

allrow=mcursor.fetchall( )

for row in allrow:

if row[0]==eno:

print(row)

mycon.close( )

RESULT:
Thus the given program executed successfully.

OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM USING PENCIL
ALONG WITHIN THE BOX)
Py-> sql is connected

Enter num : 103

(103,’Cinu , 43, ‘Namakkal’)


25. INTEGRATE SQL WITH PYTHON - DELETING A RECORD FROM TABLE

AIM: To integrate SQL with Python by importing the MySQL module to search a student using
rollno and delete the record.

PROGRAM :

import mysql.connector as mc

mycon=mc.connect(host='localhost',user='root',passwd='root1',database='db12')

if mycon.is_connected():

print("Py->Sql connected")

eno=int(input("Enter num:"))

mcursor=mycon.cursor()

mcursor.execute("select * from emp")

allrow=mcursor.fetchall()

for row in allrow:

if row[0]==eno:

mcursor.execute("delete from emp where eno={}".format(eno))

mcursor.execute("select * from emp")

print(mcursor.fetchall())

mycon.commit()

mycon.close()

RESULT:

Thus the given is program executed successfully.


OUTPUTS: (SHOULD BE WRITTEN IN LEFT HAND SIDE OF THE PROGRAM
USING PENCIL ALONG WITHIN THE BOX)

Py -> sql is
connected
Enter num
: 102
(101,’Anu’,
23,’Salem’)
(103,’Cinu’,43,’Namakkal’)
(104, ‘Nishanth’, 46,’Chennai’)
(105, ‘Nanda’, 56, ‘Erode’)

You might also like