CRM Tools
CRM Tools
CRM Tools
R16
Lab Manual
1 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
2 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
a)
Write a program to count the
numbers of characters in the string 11
and store them in a dictionary data
30-06-2017
structure
5 DS
b)
Write a program to use split and join
methods in the string and trace a
birthday with a dictionary data 12
structure.
a)
Write a program combine_lists that
combines these lists into a dictionary.
30-06-2017 12
b)
6 DS - Continued Write a program to count frequency
of characters in a given file. Can you
use character frequency to tell 13
whether the given file is a Python
program file, C program file or a text
file?
a)
Write a program to print each line of
a file in reverse order.
7 Files
06-07-2017 13
b)
Write a program to compute the
number of characters, words and
lines in a file.
14
a)
Write a function ball_collide that
takes two balls as parameters and
computes if they are colliding. Your 14
function should return a Boolean
representing whether or not the balls
8 Functions are colliding. 13-07-2017
Hint: Represent a ball on a plane as a
tuple of (x, y, r), r being the radius
3 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
4 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
a)
Install packages requests, flask and
explore them. using (pip)
12 Modules 24-08-2017 21
b)
Write a script that imports requests
and fetch content from the page. Eg.
(Wiki)
24
c)
Write a simple script that serves a
simple HTTPResponse and a simple
HTML Page
26
a)
Class variables and instance variable
13 OOP i) Robot 31-08-2017
ii) ATM Machine
34
1.
Write a GUI for an Expression
Calculator using tk
38
14 GUI, 2.
08-09-2017
Write a program to implement the
Graphics following figures using turtle
40
a)
Write a test-case to check the
function even_numbers which return
True on passing a list of all even 42
numbers
15 Testing 21-09-2017
b)
Write a test-case to check the
function reverse_string which returns
the reversed string.
42
a)
Build any one classical
data structure.
43
16 Advanced b) 21-09-2017
Write a program to solve knapsack
problem.
45
5 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
1.
a. Running instructions in Interactive interpreter and a Python Script?
>>> 3+5
8
>>> 4-2
2
>>> 8/2
4.0
Output:
Error: Excepted an indented block
Correct Program:
n1=int(input("enter n1 value"))
n2=int(input("enter n1 value"))
if n1>n2:
print("n1 is big")
else:
print("n2 is
Output: big")
enter n1 value10
enter n1
value20 n2 is
big
6 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
2.
a. Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem)
import math;
x1=int(input("Enter x1--->"))
y1=int(input("Enter y1--->"))
x2=int(input("Enter x2--->"))
y2=int(input("Enter y2--->"))
Output:
Enter x1--->10
Enter y1---
>20 Enter
x2--->15
Enter y2--->19
Distance
between two
points:
5.0990195135
927845
step 1: open notepad and write the below program
b. Write a program add.py that takes 2 numbers as command line arguments and prints
import
its sum. sys;
n1=int(sys.argv[1]);
n2=int(sys.argv[2]);
print (n1+n2)
step 2: SAVE
a. Write a Program for checking whether the given number is a even number or not.
n=int(input("Enter a number---->"))
if n % 2 == 0:
print ("EVEN Number");
else:
print ("ODD
Number");
Output:
Enter a number---->10
EVEN Number
Enter a number---->11
ODD Number
b. Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10
i=1;
for j in range(2,10):
print("i:",i,"j:",j)
print(i,"/",j)
print (i/j);
Output:
i: 1 j: 2
1/2
0.5
i: 1 j: 3
1/3
0.3333333333333333
i: 1 j: 4
1/4
0.25
i: 1 j: 5
1/5
0.2
i: 1 j: 6
1/6
0.16666666666666666
8 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
i: 1 j: 7
1/7
0.14285714285714285
i: 1 j: 8
1/8
0.125
i: 1 j: 9
1/9
0.1111111111111111
c. Write a program using a for loop that loops over a sequence. What is sequence ?
Output:
a
m
y
t
e
l
o
9 | Page
p
r
2nd Year- 1st Semester Python Programming Lab | 2017-18
d. Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.
n = int(input("Enter A Number--->"));
while n >=0:
print (n);
n = n -
1;
Output:
Enter A Number--->10
10
9
8
7
6
5
4
3
2
1
0
4.
a. Find the
sum of all the
primes below
two million.
Each new term in the
Fibonacci sequence
a, b = is 1, 2
generated by adding 0
total =
the previousprint(a,end="
two ")
while (a
terms.
<=2000000-1):
By starting
if a %with 2 !=1 and
0:2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21,
total +=34, 55, 89,...
a
a, b = b, a+b
print(a,end=" ")
print("\n sum of
prime numbers term
in fibonacci series:
Output:
",total)
10 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040 1346269 2178309
sum of prime numbers term in fibonacci series: 2435422
b. By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even-valued terms.
a, b = 1, 2
total = 0
print(a,end=" ")
while (a
<=4000000-1):
if a % 2 == 0:
total +=
a
a, b = b, a+b
print(a,end=" ")
print("\n sum of
prime numbers term
Output:in fibonacci series:
",total)
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368
75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887
sum of prime numbers term in Fibonacci series: 4613732
5.
a. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
(OR)
str=input("Enter a String")
dict = {}
for i in str:
11 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
dict[i] = str.count(i)
print (dict)
Output:
(OR)
str=input("Enter a String")
dist={}
L=len(str);
d={str:L};
print(d)
Output:
Enter a Stringguntur
{'guntur': 6}
b. Write a program to use split and join methods in the string and trace a birthday with
a dictionary data structure.
a="hi i am python programmer"
b=a.split()
print (b)
c=" ".join(b)
print(c)
Output:
6.
a. Write a program combine_lists that combines these lists into a dictionary.
l1=[1,2,'cse',4,5]
l2=['khit',7,'cse',9]
l=l1+l2
d={}
for i in
range(len(l)):
d[i]=l[i]
12 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Output:
The dictionary is------> {0: 1, 1: 2, 2: 'cse', 3: 4, 4: 5, 5: 'khit', 6: 7, 7: 'cse', 8: 9}
---------------------------------------------OR--------------------------------
l=[1,'python',4,7]
k=['cse',2,'guntur',8]
m=[]
m.extend(l);
m.extend(k);
print(m)
d={1:l,2:k,'combine_list':m}
print(d)
Output:
Output:
b. Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C
program file or a text file?
import os
count =0
file=open("D:/a.txt")
for line in file:
for l in range(0,len(line)):
count+=1;
print("count:",count)
filename,file_extension=os.path.splitext("D:/a.txt");
13 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
print("file_extension==",file_extension);
if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
rint("its a c program
file");
count: 2
file_extension== .txt
its a txt file
7.
a.
Write a
input_file=open('D:/a.txt','r')
program to
for line in input_file:
print each
l=len(line)
line of a
s=' '
file
in reverse
while(l>=1):
order. s=s+line[l-1]
l=l-1
print(s)
input_file.close()
Output:
tihk
b. Write a program to compute the number of characters, words and lines in a file.
k=open('D:/a.txt','r')
char,wc,lc=0,0,0
for line in k:
for k in range(0,len(line)):
char +=1
if(line[k]==' '):
wc+=1
if(line[k]=='\n'):
wc,lc=wc+1,lc+1
14 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
a.txt contain
khit
Guntur
Hyderabad
Output:
The no. of chars is 21
The no. of words is
2
The no. of lines is 2
8.
a. Write a function ball_collide that takes two balls as parameters and computes if
they are colliding. Your function should return a Boolean representing whether or
not the balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
If (distance between two balls centers) <= (sum of their radii) then (they are colliding)
import math
def ball_collide(x1,y1,r1,x2,y2,r2):
dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls:",dist)
center=dist/2;
print("Collision point",center);
r=r1+r2;
print("Sum of radious",r)
if(center<=r):
print("They are Colliding")
return True;
else:
print("Not Colliding")
return False;
c=ball_collide(4,4,3,2,2,3)
print(c)
15 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
c=ball_collide(100,200,20,200,100,10)
print(c)
Output:
Output:
Mean 19.9
Median 13.5
Mode 18
9.
a. Write a function nearly_equal to test whether two strings are nearly equal. Two
strings a and b are nearly equal when a can be generated by a single mutation on
b.
16 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
else:
print("Both Strings are Different")
Output:
b. Write a function
dups to find all duplicates
def
in the list.FindDuplicates(list):
for i in list:
count = list.count(i)
if count > 1:
print ('There are duplicates in list')
return True
print ('There are no duplicates in list'
) return False
Output:
return True
print ('There are unique elements in list'
) return False
Output:
Output:
1
2
6
24
120
720
5040
40320
362880
3628800
18 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
b. Write a function reverse to reverse a list. Without using the reverse function.
l = [1,2,3,4,5]
print (l[::-1])
Output:
[5, 4, 3, 2, 1]
c. Write function to compute gcd, lcm of two numbers. Each function shouldn’t
exceed one line.
import fractions
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2
value:")) gcd = fractions.gcd(n1,
n2) print("GCD value is:",gcd)
def lcm(n, m):
return n * m / gcd
print("LCM value
is:",int(lcm(n1,n2)))
Output:
Enter n1 value: 5
Enter n2 value:
9 GCD value is:
1 LCM value is:
45
11.
a. Write
row=int(input("Enter
a program that No of Rows for 1st Matrix:"))
column=int(input("Enter
defines a matrix and No of column for 1nd Matrix:"))
row1=int(input("Enter No of Rows for 2st Matrix:"))
prints
column1=int(input("Enter No of column for 2nd Matrix:"))
X = [[int(input(("Enter value for X[",i,"][",j,"]:"))) for j
in range(column)] for i in range(row)]
Y = [[int(input(("Enter value for Y[",i,"][",j,"]:"))) for j
in range(column1)] for i in range(row1)]
19 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Output:
for r in result:
21 | Page print(r)
2nd Year- 1st Semester Python Programming Lab | 2017-18
else:
print("Multiplication is not possible")
Output:
12.
22 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
23 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
24 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
25 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
5. Install flask
6. Install virtualenv
26 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
b. Write a script that imports requests and fetch content from the page. Eg. (Wiki)
I. First you need to install Wikipedia
27 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
import wikipedia
print(wikipedia.summary("wikipedia"))
wikipedia.search("branch")
ny=wikipedia.page("new york")
ny.title
ny.url
ny.contentny.links[0]
wikipedia.set.long["for"]
wikipedia.summaru("facebo
ok",sentences=1)
Output:
Wikipedia ( ( listen) WIK-i-PEE-dee-ə or ( listen) WIK-ee-PEE-dee-ə) is a free online
encyclopedia with the aim to allow anyone to edit articles. Wikipedia is the largest and most
popular general reference work on the Internet, and is ranked the fifth-most popular website.
Wikipedia is owned by the nonprofit Wikimedia Foundation.
Wikipedia was launched on January 15, 2001, by Jimmy Wales and Larry Sanger. Sanger coined
its name, a portmanteau of wiki and encyclopedia…………………………
28 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Manhattan
c. Write a simple script that serves a simple HTTPResponse and a simple HTML Page
I. install django
29 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Running this command creates a skeleton django app with the following structure:
helloapp
├─helloapp
│ ├── init .py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
30 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Running this command will create an app called howdy. Your file structure should
now look something like this.
helloapp
├── helloapp
│ ├──
│ init .py
│ ├── settings.py
│ ├── urls.py
├── howdy└── wsgi.py
│ ├──
│ init .py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
└── manage.py
└── views.py
V. now open settings.py in helloapp and change installed app to
# helloapp/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'howdy'
]
32 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
VI.
33 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
If you look carefully, you will see a warning that you have unapplied migrations.
Ignore that for now. Go to your browser and access http://127.0.0.1:8000/.
VII. Press control+break buttons you will come out from it.
34 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
VIII. Migrations make it easy for you to change your database schema (model)
without having to lose any data. Any time you create a new database model,
running migrations will update your database tables to use the new schema
without you having to lose any data or go through the tedious process of
dropping and recreating the database yourself.
python manage.py migrate
# helloapp/urls.py
from django.conf.urls import url,
include from django.contrib import
admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',
include('howdy.urls')),
]
35 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Save it
X. Now run server
36 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Let's fix that. Go to the howdy app folder and create a file called
urls.py. The howdy app folder should now look like this.
├── howdy
│ ├── init .py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├──
init .py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
urlpatterns = [
url(r'^$',
views.HomePageView.as_view()
),
]
This code imports the views from
our howdy app and expects a view
called
37 HomePageView to be defined. Since we don't have one, open the views.py file
| Page
in the howdy app and write this code.
2nd Year- 1st Semester Python Programming Lab | 2017-18
# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
This file defines a view called HomePageView. Django views take in a request and
return a response. In our case, the method get expects a HTTP GET request to the
url defined in our urls.py file. On a side note, we could rename our method to post
to handle HTTP POST requests.
Once a HTTP GET request has been received, the method renders a template
called index.html which is just a normal HTML file which could have special Django
template tags written alongside normal HTML tags. If you run the server now, you
will see the following error page:
13.
a. Class variables and instance variable and illustration of the self variable
I.
class Robot
Robot:
population=0
def init (self, name):
self.name = name
print('(Initializing
{0})'.format(self.nam
e))
Robot.population += 1
def del (self):
print('{0} is
being
destroyed!'.format(se
lf.name))
Robot.population
-= 1
if
Robot.population ==
0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots
working.'.format(Robot.population))
def sayHi(self):
print('Greetings, my
masters call me
{0}.'.format(self.name))
38 | Page def howMany():
print('We have {0:d}
robots.'.format(Robot.population))
howMany = staticmethod(howMany)
d=Robot('R1-D1')
d.sayHi()
Robot.howMany()
2nd Year- 1st Semester Python Programming Lab | 2017-18
d1=Robot('R2-D2')
d1.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy
them.")
del d
del d1
Robot.
howMan
y()
Output:
(Initializing R1-D1)
Greetings, my masters call me R1-D1.
We have 1 robots.
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 2 robots.
II. ATM
class Bank:
Account_type = "Savings"
location = "Guntur"
def init (self, name, Account_Number,balance):
self.name = name
self.Account_Number = Account_Number
self.balance=balance
self.Account_type=Bank.Account_type
self.location=Bank.location
if(account_pin==123):
Account(self)
else:
print("Pin Incorrect. Please try
again") Error(self)
return '
'.join([self.name,self.Account_Number])
def Error(self):
""")
option=int(input("Please enter your choice:"))
if(option==1):
Balance(self)
elif(option==2):
Withdraw(self)
elif(option==3):
Deposit(self)
elif(option==4):
exit()
def Balance(self):
print("Balance:",self.balance)
Account(self)
def Withdraw(self):
w=int(input("Please Enter Desired amount: "))
if(self.balance>0 and self.balance>=w):
self.balance=self.balance-w
print("Your transaction is successfull")
print("your Balance:",self.balance)
print("")
else:
print("Your transaction is cancelled due to")
print("Amount is not sufficient in your account")
40 | Page Account(self)
2nd Year- 1st Semester Python Programming Lab | 2017-18
def Deposit(self):
d=int(input("Please Enter Desired amount: "))
self.balance=self.balance+d
print("Your transaction is successfull")
print("Balance:",self.balance)
Account(self)
def Exit():
print ("Exit")
t1 = Bank('mahesh', 1453210145,5000)
print (t1)
Output:
41 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
1) Balance
2) Withdraw
3) Deposit
4) Quit
14.
a. Write a GUI for an Expression Calculator using tk.
import tkinter as tk
from tkinter import *
root = Tk()
buttons = {}
signVal =
'' firstVal
= 1
root.title('Calculator')
root.attributes("-toolwindow", 1)
42 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
def createNumbers():
global buttons
buttonNum = 0
for b in range( 2 ):
for b2 in range(
5 ):
button = Button(frame2, text = buttonNum, font =
"Courier 9", width = 7, bd = 3 )
button.grid(row=b
, column=b2) buttons[ button
] = buttonNum buttonNum += 1
button.bind( "<Button-1>", makeChoice )
def operators():
button = Button(frame2, text = '+', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('+') )
button.grid(row=2, column=0)
button = Button(frame2, text = '-', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('-') )
button.grid(row=2, column=1)
button = Button(frame2, text = '*', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('*') )
button.grid(row=2, column=2)
button = Button(frame2, text = '/', font = "Courier 9",
width = 5, bd = 3, command = lambda : operation('/') )
button.grid(row=2, column=3)
button = Button(frame2, text = '=', font = "Courier 9",
width = 5, bd = 3, command = lambda : excutionPart('=') )
button.grid(row=2, column=4)
button = Button(frame2, text = 'Clear', font = "Courier
9", width = 5, bd = 3, command = lambda : clearAll('clear') )
button.grid(row=3, column=0)
def makeChoice( event ):
global buttons
if (v.get() is None) or (len(v.get()) == 0):
v.set(buttons[ event.widget ])
else:
v.set(str(v.get())+str(buttons[ event.widget ]))
def operation(value):
try:
global
signVal global
firstVal
signVal = value
if not isinstance(v.get(), int):
firstVal = int(v.get())
else:
tkMessageBox.showerror("Error","Wrong Formate")
print ("First Value :", firstVal)
v.set('')
except TypeError:
tkMessageBox.showerror("Error","Wrong Formate")
43 | Page def excutionPart(ex):
2nd Year- 1st Semester Python Programming Lab | 2017-18
Output:
44 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
Output:
import turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
painter = turtle.Turtle()
painter.fillcolor('blue')
45 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
painter.pencolor('blue')
painter.pensize(3)
for i in range(1,180):
painter.left(18)
drawsq(painter, 200)
Output:
15.
a. Write a test-case to check the function even_numbers which return True on
passing a list of all even numbers
import unittest
def even_numbers(ls):
i=0
for i in range(len(ls)):
if ls[i]%2 == 0:
i=i+1
else:
r
eturn
False
return
True;
class Test(unittest.TestCase):
def test_even_numbers(self):
ls=[2,4,6,8,12]
print( even_numbers(ls))
self.assertEqual(True, even_numbers(ls))
46 | Page unittest.main()
2nd Year- 1st Semester Python Programming Lab | 2017-18
Output:
True
.
OK
b. Write a test-case to check the function reverse_string which returns the reversed
string.
import unittest
def reverse(s):
return s[::-1]
class Test(unittest.TestCase):
def test_reverse(self):
s="mahesh"
print( reverse(s))
self.assertEqual("hseham", reverse(s))
unittest.main()
Output:
hseham
.
OK
16.
a. Build
any one classical data
class Stack:
structure.
# initialize an empty list (stack)
def init (self):
self.mStack = []
47 | Page
2nd Year- 1st Semester Python Programming Lab | 2017-18
print
("---------------------------------")
print( "Implementation of Stack in
Python") print
("---------------------------------")
while True:
user_input = int(input("Enter the option: "))
if user_input == 1:
mStack.view()
elif user_input == 2:
item = (input("Enter the item to be inserted: "))
mStack.push(item)
elif user_input == 3:
mStack.pop()
elif user_input == 4:
print (mStack.size())
elif user_input == 5:
print (mStack.top())
elif user_input == 6:
break
Output:
Menu items
1. View the stack
2. Push item into stack
3. Pop item out of stack
4. Get the size of stack
5. Get the top item in stack
6. Quit the program
Enter the option: 1
No item in stack
Enter the option: 2
Enter the item to be
inserted: 10
Inserted item: 10
Enter the option: 2
Enter the item to
be inserted: 20
Inserted item: 20
Enter the option: 2
Enter the item to
be inserted: 30
Inserted item: 30
Enter the option: 1
49 | Page 10
20
2nd Year- 1st Semester Python Programming Lab | 2017-18
30
Enter the option: 4
3
Enter the option: 5
30
Enter the option: 3
Removed item :
30 Enter the
option: 1 10
20
Enter the option:6
b. Write a program to
solve knapsack
problem.
def knapSack(W, wt, val, n):
K = [[0 for x in range(W+1)] for x in range(n+1)]
for i in range(n+1):
for w in range(W+1):
if i==0 or
w==0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] =
max(val[i-1]
+ K[i-1][w-
wt[i-1]],
K[i-1][w])
else:
K[i][w] = K[i-1]
[w]
return K[n][W]
val = [5, 3, 4]
wt = [3, 2, 1]
W = 5
n = len(val)
print(knapSack(W, wt, val, n))
Output:
50 | Page
II-I Semester (R16) Data structure through C++ Lab (2017-18)
R16
Lab Manual
1
II-I Semester (R16) Data structure through C++ Lab (2017-18)
2
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include<iostream.h>
#include<conio.h>
class poly
{
struct
{ int coef;
int
expo;
} term[20];
int degree;
public:
void
input()
{ int i;
cout<<"Enter number of
terms"; cin>>degree;
cout<<"Enter coefficients and exponents for " << degree
<<" terms"<<endl;
for(i=0;i<degree;i++)
cin>>term[i].coef>>term[i].expo;
}
void add(poly A, poly B)
{
int i,j,k,l;
degree=A.degree+B.degree;
i=0;j=0;k=0;
while(i<A.degree &&
j<B.degree)
{
if( A.term[i].expo<B
.term[j].expo)
{ term[k].coef=B.term[j].coef;
term[k].expo=B.term[j].expo;
j++;
k++;
}
if( A.term[i].expo>B.term[j].ex
po)
{ term[k].coef=A.term[i].coef;
term[k].expo=A.term[i].expo;
i++;
k++;
}
if( A.term[i].expo==B.term[j].e
xpo)
{ term[k].coef=A.term[i].coef+B.term[j].coef;
term[k].expo=A.term[i].expo;
i+
+;
j++;
k+ 3
+;
}
}
if(i<A
.degre
e)
{
II-I Semester (R16) Data structure through C++ Lab (2017-18)
term[k].expo=A.term[l].expo;
k++;
}
}
if(j<B.degree)
{ for(l=j; l<B.degree; l++)
{ term[k].coef=B.term[l].coef;
term[k].expo=B.term[l].expo;
k++;
}
}
degree=k;
}
void display()
{ int i;
cout<<"polynomial is"<<endl;
for(i=0;i<degree;i++)
cout<<term[i].coef<<"x"<<ter
m[i].expo<<" ";
}
};
main()
{
poly A,B,C;
cout<<"Enter Polynomial A:"<<endl;
A.input();
cout<<"Enter Polynomial B:"<<endl;
B.input();
C.add(A,B);
C.display();
getch();
}
Output:
Enter Polynomial A:
Enter number of terms 3
Enter coefficients and exponents for 3 terms
3 2 4 1 6 0
Enter Polynomial B:
Enter number of terms 3
Enter coefficients and exponents for 3 terms
5 2 5 1 8 0
Polynomial is
8x2 9x1 14x0
4
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include <iostream.h>
#define max 10
class multistack
{
int top1, top2, stk_arr[max];
public:
multistack()
{
top1=-1;
top2=max;
}
void
push()
{
int x,ch;
if(top1==top2-1)
{
cout<<"stack overflow "<<endl;
return;
}
cout<<"enter a no \n";
cin>>x;
cout<<"\n press 1 to push in stack1 or press 2 for stack2:";
cin>>ch;
if(ch==1)
stk_arr[++top1]=x;
else
stk_arr[--
top2]=x;
cout<< x <<" element is successfully pushed \
n"; return;
}
void pop()
{
int y,ch;
cout<<"\n press 1 to pop from stack1 or press 2 for
stack2"; cin>>ch;
if(ch==1)
{
if(top1==-1)
{
cout<<"stack underflow\
n"; return;
}
y=stk_arr[top1]
;
stk_arr[top1--]=0;
}
else
{
if(top2==max)
{ 5
cout<<"stack
underflow\n";
II-I Semester (R16) Data structure through C++ Lab (2017-18)
return;
}
y=stk_arr[top2];
stk_arr[top2++]=0;
}
cout<<y<< "\n element is successfully poped from stack \n";
return;
}
void display()
{
int i;
if (top1 == -1)
{
cout<<"stack 1 is empty \n";
}
else
{
cout<<"elements of Stack 1 are : \n";
for (i = 0; i <= top1; i++)
{
cout<<stk_arr[i]<<endl;
}
}
if (top2 == max)
{
cout<<"stack 2 is empty \n";
}
else
{
cout<<"elements of Stack 2 are : \n";
for (i = max-1; i >= top2; i--)
{
cout<<stk_arr[i]<<endl;
}
}
return ;
}
};
main()
{
multistack s;
int ch;
do
{
cout<<"\n 1:push\n 2:pop\n 3:display\n 4:exit\n choice:";
cin>>ch;
switch (ch)
{
case 1:s.push();
break;
case 2:s.pop();
6
II-I Semester (R16) Data structure through C++ Lab (2017-18)
break;
case 3:s.display();
break;
case 4:cout<<"exiting from program\n";
break;
default:cout<<"wrong choice\n";
break;
}
}while(ch!=4);
Output:
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a
no 10
Press 1 to push in stack 1 or press 2 for stack 2 : 1
10 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a no 20
Press 1 to push in stack 1 or press 2 for stack 2 : 1
20 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 1
Enter a
no 100
Press 1 to push in stack 1 or press 2 for stack 2 : 2
100 element is successfully pushed
1:Push
2:Pop
3:Display
4:Exit
Choice: 3
Elements
of stack 7
1 are:
II-I Semester (R16) Data structure through C++ Lab (2017-18)
20
10
Elements of stack 2 are:
200
100
1:Push
2:Pop
3:Display
4:Exit
Choice: 2
Press 1
to pop
from
stack 1
or press
2 for
stack 2: 1
20
Element is successfully poped from stack
1:Push
2:Pop
3:Display
4:Exit
Choice: 2
Press 1
to pop
from
stack 1
or press
2 for
stack 2: 2
200
Element is successfully poped from stack
1:Push
2:Pop
3:Display
4:Exit
Choice: 3
Elements of stack 1 are:
10
Elements of stack 2 are:
100
8
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include <iostream.h>
#define max 5
class cqueue
{
int front,rear, cq[max];
public:
cqueue()
{
front= -1;
rear = -1;
}
void insert()
{
int x;
if(front==(rear+1)%max )
{
cout<<"Circular queue overflow "<<endl;
return;
}
cout<<"enter a no \n";
cin>>x;
rear=(rear+1)%max;
cq[rear]=x;
if(front==-1) front=0;
}
void del()
{
int y;
if(front==rear &&
rear==-1)
{
cout<<"circular queue underflow\n";
return;
}
y=cq[front];
cq[front]=0;
if(front==rear)
front=rear
=-1;
else
front=(fro
nt+1)%max;
}
void display()
{
int i;
if (front==rear 9
&& rear==-1)
{
II-I Semester (R16) Data structure through C++ Lab (2017-18)
main()
{
cqueue q;
int ch;
do
{
cout<<"\n 1:insert\n 2:del\n 3:display\n 4:exit\n choice:";
cin>>ch;
switch (ch)
{
case 1:q.insert();
break;
case 2:q.del();
break;
case 3:q.display();
break;
case
4:cout<<"exiting
from program\n";
break;
default:cout<<"wrong choice\n";
break;
}
}while(ch!=4);
}
Output:
1:insert
2:del
3:display
4:exit
Choice :1
Enter a no 10
1:insert
2:del
3:display
10
II-I Semester (R16) Data structure through C++ Lab (2017-18)
4:exit
Choice : 1
Enter a no 20
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 30
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 40
1:insert
2:del
3:display
4:exit
Choice : 1
Enter a no 50
1:insert
2:del
3:display
4:exit
Choice :
3
Elements of circular queue are:
10
20
30
40
50
1:insert
2:del
3:display
4:exit
Choice : 1
Circular queue overflow
1:insert
2:del
3:display
4:exit
11
II-I Semester (R16) Data structure through C++ Lab (2017-18)
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice : 3
Elements of circular queue are: 40
50
1:insert
2:del
3:display
4:exit
Choice : 2
1:insert
2:del
3:display
4:exit
Choice :2
Circular queue underflow
1:insert
2:del
3:display
4:exit
Choice :4
12
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include<iostream.h>
class Node
{
public:
int data;
Node* next;
};
class
List:public
Node
{
Node *start;
public:
List()
{
start=
NULL;
}
void
create()
{int
num;
Node *temp=new
Node;
if(start==NULL)
{
cout<<"\nEnter an
Element:"; cin>>num;
temp->data=num;
temp-
>next=NULL;
start=temp;
}
else
{
cout<<"single linked list has an Elements, can not create new
list";
}
}
void insert()
{
Node
*prev,*last; int
count,pos,ch,num;
Node *temp=new Node;
cout<<"\nEnter an
Element:"; cin>>num;
temp-
>data=num;
temp->next=NULL; 13
cout<<"\
nINSERT
AS\n1:startNODE\
n2:LASTNODE\
n3:At
II-I Semester (R16) Data structure through C++ Lab (2017-18)
temp->next=start;
start=temp;
break;
case 2:
last=start;
while(last-
>next!
=NULL)
last=last->next;
last->next=temp;
break;
case 3:
Node *p,*n;
cout<<"\nEnter the Position to
Insert:"; cin>>pos;
n=start;
while(count!=pos)
{
p=n;
n=n-
>next;
count++;
}
if(count=
=pos)
{
p-
>next=temp;
temp->next=n;
}
else
cout<<"\nNot Able to Insert";
break;
}
}
void del()
{
Node
*prev,*last=start; int
count=1,pos,ch;
cout<<"\nDELETE\n1:startNODE\n2:LASTNODE\n3:At specific
Node"; cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:
if(start!=NULL)
{
cout<<"\nDeleted Element is "<<start-
>data; start=start->next;
}
{ else
cout<<"\nNot Able to Delete";
break; 14
case 2:
while(last->next!=NULL)
II-I Semester (R16) Data structure through C++ Lab (2017-18)
prev=last;
last=last->next;
}
cout<<"\nDeleted Element is: "<<last->data;
prev->next=NULL;
break;
case 3:
No
de
*p,*n;
cout<<"\nEnter the Position to
Insert:"; cin>>pos;
n=start;
while(count!=pos)
{
p=n;
n=n-
>next;
count++;
}
if(count==
pos)
{
cout<<"\nDeleted Element is: "<<n-
>data; p->next=n->next;
}
else
cout<<"\nNot Able to Delete";
break;
}
}
void display()
{
Node
*last=start;
if(last==NULL)
{
cout<<"\
nList is
Empty";
}
while(last!
=NULL)
{
cout<<last-
>data; cout<<"--
>"; last=last-
>next;
}
cout<<"NULL";
}
int main() 15
{
List
l; int
ch;
while(1)
{
co
II-I Semester (R16) Data structure through C++ Lab (2017-18)
\n2:INSERT\n3:DELETE\n4:DISPLAY\n5:EXIT\n";
cout<<"\nEnter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:
l.create();
break;
case 2:
l.insert();
break;
case 3:
l.del();
break;
case 4:
l.display();
break;
case 5:
return 0;
}
}
return 0;
}
Output:
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 1
Enter an element 10
*** MENU ***
1:CREATE FRIST
NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 2
Enter an element 20
Insert as
1:startNODE
2:LASTNODE
3:At specific Node
Enter your choice 1
16
II-I Semester (R16) Data structure through C++ Lab (2017-18)
2:LASTNODE
3:At specific Node
Enter your choice 3
Enter the position
to insert 3
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 4
201030NULL
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 2
Enter an element 40
Insert as
1:start node
2:last node
3:at specific node
Enter your choice 2
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 3 17
II-I Semester (R16) Data structure through C++ Lab (2017-18)
Delete
1:start node
2:last node
3:at specific node
Enter your choice 3
Enter the position to insert 2
Deleted element is 10
*** MENU ***
1:CREATE FRIST NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 4
203040NULL
*** MENU ***
1:CREATE FRIST
NODE
2:INSERT
3:DELETE
4:DISPLAY
5:EXIT
Enter your choice 5
5. Write a program to perform Binary Search Operation using divide and conques concept?
#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],i,key,n,result;
int low,mid,high;
void binarysearch(int
a[],int key,int low,int
high);
clrscr();
cout<<"how many numbers you want to enter?";
cin>>n;
cout<<"\n enter "<<n<<"elements in ascending
order\n";
for(i=0;i<n;i++)
cin>>a[i];
18 to be
cout<<"\n enter the elements
searched";
II-I Semester (R16) Data structure through C++ Lab (2017-18)
cin>>key;
low=0;
high=n-1;
binarysearch(a,key,low,high);
getch();
}
void binarysearch(int a[],int
key,int low,int high)
{
int mid;
if(low>high)
{ cout<<"Search element not found";
return;
}
else
{
mid=(low+high)/2;
if(key==a[mid])
{
cout<<"key elements is found at posion"<<mid+1;
return ;
}
if(key<a[mid])
{
high=mid-1;
binarysearch(a,key,low,high);
}
if(key>a[mid])
{
low=mid+1;
binarysearch(a,key,low,high);
}
}
}
Output:
How many numbers you want to enter? Enter 5 numbers in ascending order
10
20
30
40
50
Enter the element to be searched 10 key element is found position.
19
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include<iostream.h>
class Node
{
Public:
Node *prev;
int data;
Node *next;
};
class list:public
Node
{
Node *start;
Node *last;
public:
List(
)
{
Start=NULL;
Last=NULL;
}
void
create()
{
int
num;
Node *temp=new Node;
if(start==NULL)
{
cout<<"\n Enter an element:";
cin>>num;
temp-->prev=NULL;
temp-->data-num;
temp-->next=NULL;
start=temp;
last=temp
}
else
{
cout<<"Double
linked list has
an element,
cannot
create new list"
}
}
void insert()
{
int ch,num;
Node *temp=new Node;
cout<<"\n Enter an element";
cin>>num;
temp-->prev=NULL; 20
temp-->data-num;
temp-->next=NULL;
cout<<"\n INSERT AS \n 1:Start Node \n 2:" Last Node";
cout<<"\n Enter your choice:";
II-I Semester (R16) Data structure through C++ Lab (2017-18)
cin>>ch;
switch(ch)
{
case 1:
temp-->next=start;
start--
>prev=temp;
start=temp;
break;
case 2:
last-->next=temp;
temp--
>prev=last;
last=temp;
}
void del()
{
Node *p;
int ch;
cout<<"\n Delete \n 1:Start Node \n 2:Last Node";
cout<<"\n Enter your choice:";
cin>>ch;
switch(ch)
{
case
1:
i
f
(
s
t
a
r
t
!
=
N
U
L
L
)
{
c
o
u
t
<
<
"
\
n
d 21
e
l
e
t
e
d
II-I Semester (R16) Data structure through C++ Lab (2017-18)
{
case 1:
p=start;
if(p==NULL)
{
cout<<"\n list is empty";
return;
}
cout<<"\n
elements
from
left
to
right
are
\n";
while(p!=NULL)
{
cout<<p-->data;
cout<<"-->";
p=p-->next;
}
break;
case 2:
p
=last;
i
f(p==N
ULL)
{
cout<<"\n list is
empty"; return;
}
cout<<"\n
elements
from
right
to
left
are
\n";
while(p!=NULL)
{
22 cout<<p--
>data;
cout<<"-->";
p=p-->prev;
}
break;
}
}
II-I Semester (R16) Data structure through C++ Lab (2017-18)
case 3:
d.del();
break;
case 4:
d.display();
break;
case 5:
break;
}
}while(ch<=4);
}
Output:
***DOUBLE LINKED LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter your choice:1
Enter an element 10
***DOUBLE LINKED
LIST MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter
your
choice:1
Double
Linked
List has
an
element,
cannot
create
new list
***DOUB
LE
LINKED
LIST
MENU**
*
23
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter
II-I Semester (R16) Data structure through C++ Lab (2017-18)
5:Exit
Enter your choice:4
Display
1:left to right
2:right to
left
Enter your
choice:2
Elements from right to left are
10 20
***DOUBLE LINKED LIST
MENU***
1:create first node
2:Insert
3:Delete
4: Display
5:Exit
Enter
your
choice:5
class node
{ public:
int data;
node *left;
node *right;
};
class BST:public
node
{ public:
node *root;
BST()
{
root=NULL
;
}
void
create()
{int num;
node *temp=new node; 25
if(root==NULL)
II-I Semester (R16) Data structure through C++ Lab (2017-18)
{
cout<<"\nEnter an Element:";
cin>>num;
temp->left=NULL;
temp->data=num;
temp->right=NULL;
root=temp;
}
else
cout<<"BST has
already a Root
node";
}
void insert(node *t,
int x)
{
}
if( x > t->data )
{
if( t->right ==
NULL )
{
temp->left=NULL;
temp->data=x;
temp->right=NULL;
t->right=temp;
return;
}
else
insert(t->right,
x);
}
26
void search(node *t,int
x)
{ if(t==NULL)
II-I Semester (R16) Data structure through C++ Lab (2017-18)
"; inorder(t-
>right);
}
}
void preorder(node *t)
{
if(t !=NULL)
{
cout<<t->data<<"
"; preorder(t-
>left); preorder(t-
>right);
}
}
";
}
}
}; {
void main() 27
{
int
ch,x;
BST b;
do
II-I Semester (R16) Data structure through C++ Lab (2017-18)
case 4:
b.inorder(b.root);
break;
case 5:
b.preorder(b.root);
break;
case 6:
b.postorder(b.root);
break;
case 7:
break;
}
}while(ch<=6);
getch();
}
Output:
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:1
Enter an element 50
**** BST MENU ****
28
II-I Semester (R16) Data structure through C++ Lab (2017-18)
29
II-I Semester (R16) Data structure through C++ Lab (2017-18)
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:2
Enter an element 70
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:4
20 30 40 50 70 80 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:5
50 30 20 40 80 70 90
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
30
II-I Semester (R16) Data structure through C++ Lab (2017-18)
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:6
20 40 30 70 90 80 50
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:3
Enter an element 80
Element found in the BST
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:1
BST has already root
node
**** BST MENU ****
1:CREATE ROOT NODE
2:INSERT
3:SEARCH
4:INORDER
5:PREORDER
6:POSTORDER
7:EXIT
Enter Your Choice:7
31
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include <iostream.h>
#include <conio.h>
#define SIZE 7
class node
{public:
int data;
node *next;
} ;
class
hashtable :
public node
{
public:
node *htable[SIZE];
hashtable()
{
int i ;
node *t;
for(i =
0; i <
SIZE; i+
+)
{
t=new
node;
t->data = NULL;
t->next =
NULL;
htable[i]=t;
}
}
void insert(int n)
{
int index ;
index=hash(n);
if( htable[ind
ex]->data !=
NULL )
{
resolve(htab
le[index],in
dex, n);
}
else
{
htable[index]
->data=n;
}
} 32
int hash(int n)
{
return(n
%SIZE);
}
II-I Semester (R16) Data structure through C++ Lab (2017-18)
p=t;
while(p->next != NULL)
p = p->next;
void display()
{
int i = 0;
node
*target;
for(i = 0; i < SIZE;
i++)
{
if(htable[i]->data
!= NULL)
{
target = htable[i];
while(target)
{
cout<<"\nlocation: "<< i <<" data:" << target->data;
target = target->next;
}
}
}
}
};
int main(void)
{
int n,i;
hashtable h;
clrscr();
cout<<"\nEnter any 5 integer numbers\n";
for(i=0;i<=4;i++)
{
cin>>n;
h.insert(n);
}
h.display();
getch();
}Output:
Enter any 5 integer numbers
10
33
II-I Semester (R16) Data structure through C++ Lab (2017-18)
20
21
36
49
Location:0 data :21
Location:0 data :49
Location :1 data :36
Location :3 data :10
Location :6 data :20
#include <iostream.h>
#include <conio.h>
int stack[10],top=-1;
void push(int item)
{
top=top+1;
stack[top]=item;
int pop()
{
int item;
if (top != -1)
{ item=stack[top];
top=top-1;
return(item);
}
}
"; x=start;
for(i=0;i<n;i++) 34
{
if(graph[x][i]==1 &&
v[i]!=1)
II-I Semester (R16) Data structure through C++ Lab (2017-18)
{
push(i);
v[i]=1;
}
}
if(top==-1)
break;
}
void main()
{
int graph[10][10];
int i,j,n,v1,v2;
char ch,type;
clrscr();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
graph[i][j]=0 ;
}
do
{
cout<<"Enter the Edge of graph";
cin>>v1>>v2;
graph[v1-1][v2-1]=1;
graph[v2-1][v1-1]=1;
cout<<"Another edge y/n?";
cin>>ch;
}
while(ch=='y');
cout<<"The Depth First Traversal of graph is\n";
DFT(graph,n,0);
getch();
}
Output:
Enter numbers of vertices 5
Enter the edge of graph 0 1
Another edge y/n? y
Enter the edge of the graph 02
Another edge y/n? y
Enter the edge of graph 03
35
II-I Semester (R16) Data structure through C++ Lab (2017-18)
void insert(int n)
{
if(rear<=5)
{
rear++;
queue[rear]=n;
}
}
int isempty()
{
if (front==rear )
return 1;
else
return 0;
}
int del()
{ int n; if(!
isempty())
{
front++;
n=queue[front];
return n;
}
}
insert(start); 36
II-I Semester (R16) Data structure through C++ Lab (2017-18)
v[start]=1;
while(!isempty())
{ start=del();
cout<<start+1<<"
"; for(i=0;i<n;i++)
{
if(graph[start]
[i]==1 &&
v[i]==0)
{
insert(i);
v[i]=1;
}
}
}
void main()
{
int graph[10][10];
int i,j,n,v1,v2;
char ch,type;
clrscr();
do
{
cout<<"Enter the Edge of graph";
cin>>v1>>v2;
graph[v1-1][v2-1]=1;
graph[v2-1][v1-1]=1;
cout<<"Another edge y/n?";
cin>>ch;
} while(ch=='y');
getch();
}
Enter the edge of graph 0 1
Output: 37
Enter numbers of vertices 5
II-I Semester (R16) Data structure through C++ Lab (2017-18)
clrscr();
cout<<"\n Enter the number of Verteces:";
cin>>n;
cout<<"\n Enter the adjacency matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
cout<<"\n";
while(nedge<n)
{
min=999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0) 38
{
min=cost[i][j];
a=u=i;
II-I Semester (R16) Data structure through C++ Lab (2017-18)
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
cout<<"\n Edge "<<nedge << a << "-->" << b <<" cost:"<<min;
nedge++;
mincost+=min;
visited[b]=1;
}
cost[a]
[b]=cost[b]
[a]=999;
}
cout<<"\n Minimun cost="<<mincost;
getch();
}
Output:
Enter the no of vertices: 4
Enter the adjacency matrix :
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
Enter 11 4 cost:3
Enter 21 3 cost:4
Enter 33 2 cost:2
Minimum cost =9
#include<iostream.h>
#include<conio.h>
int i,j,k,a,b,u,v,n,nedge=1;
int min,mincost=0,cost[9][9];
void main()
{
clrscr();
cout<<"\nEnter the no. of vertices\n";
cin>>n;
cout<<"\nEnter the cost adjacency matrix\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;
39
II-I Semester (R16) Data structure through C++ Lab (2017-18)
}
}
cout<<"\nThe edges of Minimum Cost Spanning Tree are\n\n";
while(nedge<n)
{ min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
cout<<"("<<a<<"--
>"<<b<< ")
="<<min<<"\n";
mincost +=min;
nedge++;
cost[a]
[b]=cost[b]
[a]=999;
}
cout<<"\n\tMinimum cost = "<<mincost;
getch();
Output:
}
Enter the no of vertices: 4
Enter the cost adjacency matrix :
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
The edges of minimum cost spanning tree are
(23)=2
(14)=3
(13)=4
Minimum cost=9
40
II-I Semester (R16) Data structure through C++ Lab (2017-18)
#include<iostream.h>
#include<conio.h>
void dij(int n,int v,int cost[10][10],int dist[])
{
int i,j,u,count,flag[10],min;
for(i=1;i<=n;i++)
{flag[i]=0;
dist[i]=cost[v][i];
}
count=2;
flag[1]=1;
while(count<n)
{
min=99;
for(j=1;j<=n;j++)
if(dist[j]<min &&
!flag[j])
{min=dist[j];
u=j;
}
flag[u]=1;
for(j=1;j<=n;j++)
if((dist[u]
+cost[u]
[j]<dist[j])
&& !flag[j])
dist[j]=dist[u
]+cost[u][j];
count++;
}
}
void main()
{
int
n,v,i,j,cost[10]
[10],dist[10];
clrscr();
cout<<"\n Enter the number of nodes:";
cin>>n;
cout<<"\n Enter the cost matrix:\n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
}
cout<<"\n Enter the source :";
cin>>v;
dij(n,v,cost,dist); cout<<"\
n Shortest path:\n";
for(i=1;i<=n;i++)
if(i!=v) 41
cout<<v <<"->
"<<i <<
"cost=" <<
dist[i] <<"\
n";
getch();
}
II-I Semester (R16) Data structure through C++ Lab (2017-18)
Output:
Enter the no of vertices: 4
Enter the cost matrix:
0 6 4 3
6 0 2 5
4 2 0 7
3 5 7 0
Enter the source: 2
Shortest path:
21 cost =6
23 cost=2
24
cost=5
14. Write a
program to
#include<iostream.h>
implement
#include<conio.h>
Merge Sort?
if(left<right)
{
mergesort(array,left,mid);
mergesort(array,mid+1,right);
merge(array,left,mid,right);
}
}
int tempArray[50];
int n,i;
int pos=0, lpos =
left, rpos = mid +
1;
n=right-left+1;
while(lpos
<= mid &&
rpos <=
right)
{ 42
if(array[lpos] < array[rpos])
tempArray[pos++] = array[lpos++];
else
tempArray[pos++] = array[rpos++];
II-I Semester (R16) Data structure through C++ Lab (2017-18)
void main()
{
int n;
int
array[20];
int i;
cout<<"Enter No of
Elements"; cin>>n;
cout<<"Enter Numbers
" ;
for(i = 0;i <
n;i++)
cin>>array[i];
";
Output:
Enter no of elements 5
getch();
} numbers 5 3
Enter
25
18
4
45
Sorted array is
4 18 25 45 53
#include<iostream.h>
#include<conio.h>
43
II-I Semester (R16) Data structure through C++ Lab (2017-18)
j--; if(i<=j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[first];
a[first]=temp;
quick(a,first,
j-1);
quick(a,j+1,la
st); }
}
void main()
{
int a[50];
int n,i;
clrscr();
cout<<"\n enter n value";
cin>>n;
cout<<"\n Enter numbers
";
for(i=0;i<n;i++)
cin>>a[i];
Output:
quick(a,0,n-1);
Enter n value 5 sorted numbers are \n";
cout<<"the
for(i=0;i<n;i++)
Enter number 4 53 45 25 18
cout<<a[i]
The sorted numbers are<< "
"; getch();
4 18 25}45 53
44