0% found this document useful (0 votes)
6 views34 pages

DS Record

The document lists practical programming tasks, including programs for basic arithmetic, string manipulation, data structures, and algorithms. Each task is accompanied by example code and expected outputs. The tasks cover a range of topics from simple input/output to more complex operations like matrix multiplication and file handling.

Uploaded by

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

DS Record

The document lists practical programming tasks, including programs for basic arithmetic, string manipulation, data structures, and algorithms. Each task is accompanied by example code and expected outputs. The tasks cover a range of topics from simple input/output to more complex operations like matrix multiplication and file handling.

Uploaded by

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

List of Practical Programs

Sno Program
1 Write a program that takes two integers as command line
arguments and prints the sum of two integers
2 Program to display the information:
Your name, Full Address, Mobile Number, College Name,
Course Subjects

3 Program to find the largest number among ‘n’ given numbers.

4 Program that reads the URL of a website as input and displays


contents of a webpage.
5 printing of prime numbers between 1and 1000

6 program that reads set of integers and displays first and


second largest numbers
7 Program to print the sum of first ‘n’ natural numbers
8 Program to find the product of two matrices.
9 Program to find the roots of a quadratic equation
10 Write both recursive and non- recursive functions for the
following:
a. To find GCD of two integers
b. To find the factorial of positive integer
c. To print Fibonacci Sequence up to given number ‘n’
d. To convert decimal number to Binary equivalent
11 Program with a function that accepts two arguments: a list
and a number ‘n’. It
12 should displayall thenumbers in the list that are greater than
the given number ‘n’.

16 Program to find whether a given string is palindrome or not

17 Program with a function that takes two lists L1and L2


containing integer numbers as parameters. The return value
is a single list containing the pairwise sums of the numbers in
L1and L2.

18 Program to read the lists of numbers as L1, print the lists in
reverse order without using reverse function
19 Program to find mean, median, mode for the given set of
numbers in a list.
20 Program to find all duplicates in the list.
21 Program to o find all the unique elements of a list.

22 a.Program to find max and min of a given tuple of integers.


b.Write a program that combine lists L1and L2 into a
dictionary.

23 Program to find union, intersection, difference, symmetric


difference of given two sets
24 Program to display a list of all unique words in a text file
25 Program to read the content of a text file and display it on the
screen line wise with a line number followed by a colon
26 Program to analyze the two text files using set operations
27 Write a program to print each line of a file in reverse order.
28 Program to implement different kinds of the inheritance
29 Program to implement the polymorphism
30 Programs to implement Linear search and Binary search
31 Programs to implement Selection sort, Insertion sort

1. Write a program that takes two integers as command line arguments


and prints the sum of two integers.

cml1.py
import sys
sum= 0
for i in range(1,len(sys.argv)):
sum+= int(sys.argv[ i] )
print("result= ",sum)

Output:
c:/ pythonproj> py cml1.py 6 4
result= 10

2. Program to display the information:


Your name, Full Address, Mobile Number, College Name, Course
Subjects

name= input("enter name")


address= input("enter address")
phno= input("enter phno")
college= input("enter collegename")
course= input("enter Course")
subjects= input("enter subject details")
print(f'name= {name} address= {address} mobileno= {phno}
collegename= {college} cousre= {course} subject= {subjects}')
output:-
enter namelalitha
enter addressgopalpur hanamkonda telangana
enter phno999999999
enter collegenamevdpgc
enter CourseDataScience
enter subject detailsmaths stats datascience
name= lalitha address= gopalpur hanamkonda telangana
mobileno= 999999999 collegename= vdpgc cousre= DataScience
subject= maths stats datascience

3. Program to find the largest number among ‘n’ given numbers.

List1= [ ]
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
list1.append(numbers)
print("Maximum element in the list is :", max(list1))

output:
How many numbers: 5
Enter number 19
Enter number 25
Enter number 2
Enter number 200
Enter number 12
Maximum element in the list is : 200

4. Program that reads the URL of a website as input and displays


contents of a webpage.
# pip install requests
requests
url= "http:/ / d1jnx9ba8s6j9r.cloudfront.net/ blog/ wp- content/ uploads/
2017/ 06/ Python- Programming- Edureka.png"
data= requests.get(url)
file= open("py.jpg","wb")
file.write(data.content)

output:
click on py.jpg we can see the image

5.printing of prime numbers between 1and 1000


for n in range(1,1000):
ctr = 0
for i in range(1,n+1):
if n % i = = 0:
ctr = ctr + 1
if ctr = = 2:
print(n,end= " ")

output:-
2 3 5 7 1113 17 19 23 29 3137 4143 47 53 59 6167 7173 79 83 89 97 101
103 107 109 113 127 131137 139 149 151157 163 167 173 179 181191193 197 199
211223 227 229 233 239 241251257 263 269 271277 281283 293 307 311
313 317 331337 347 349 353 359 367 373 379 383 389 397 401409 419
421431433 439 443 449 457 461463 467 479 487 491499 503 509 521
523 541547 557 563 569 571577 587 593 599 601607 613 617 619 631
641643 647 653 659 661673 677 683 691701709 719 727 733 739 743
751757 761769 773 787 797 809 811821823 827 829 839 853 857 859
863 877 881883 887 907 911919 929 937 941947 953 967 971977 983 991
997
6. program that reads set of integers and displays first and second
largest numbers.
n= int(input("enter how many elements you want to enter"))
a= int(input("enter the number"))
max= a
smax= a
for i in range(n- 1):
a= int(input("enter the number"))
if a> max:# if the a value is greater than max then
smax= max
max= a
elif a> smax and a< max:# if the a value is greater than second max
and lessthan max
smax= a
print("second max= ",smax)

output:- enter how many elements you want to enter5


enter the number12
enter the number200
enter the number30
enter the number400
enter the number25
second max= 200

7. Program to print the sum of first ‘n’ natural numbers.


n= int(input("enter n value"))
sum= 0
for i in range(n):
sum+= i
print("sum= ",sum)

output:-
enter n value10
sum= 45

8. Program to find the product of two matrices.


X = [ [ 12,7,3] ,
[ 4 ,5,6] ,
[ 7 ,8,9] ]
Y = [ [ 5,8,1,2] ,
[ 6,7,3,0] ,
[ 4,5,9,1] ]
result = [ [ 0,0,0,0] ,
[ 0,0,0,0] ,
[ 0,0,0,0] ]
for i in range(len(X)):
for j in range(len(Y[ 0] )):
for k in range(len(Y)):
result[ i] [ j] += X[ i] [ k] * Y[ k] [ j]
for r in result:
print(r)

output:-
[ 114, 160, 60, 27]
[ 74, 97, 73, 14]
[ 119, 157, 112, 23]

9. Program to find the roots of a quadratic equation


# import complex math module
import cmath
a = 1
b = 5
c = 6
d = (b* * 2) - (4* a* c)
sol1= (- b- cmath.sqrt(d))/ (2* a)
sol2 = (- b+cmath.sqrt(d))/ (2* a)
print('The solution are:’,(sol1,sol2))

output:-
the solution are (- 3+0j) and (- 2+0j)

10 Write both recursive and non- recursive functions for the following:
a. To find GCD of two integers
b. To find the factorial of positive integer
c. To print Fibonacci Sequence up to given number ‘n’
d. To convert decimal number to Binary equivalent

a. To find GCD of two integers


# 1using Iteration
def gcd(a,b):
while b!= 0:
r= a%b
a= b
b= r
return(a)
a= int(input("Enter first number:"))
b= int(input("Enter second number:"))
GCD= gcd(a,b)
print("GCD is: ")
print(GCD).

Output:-
Enter first number:24
Enter second number:15
GCD is:
3

# 2 using recursion
def gcd(a,b):
if(b= = 0):
return a
else:
return gcd(b,a%b)
a= int(input("Enter first number:"))
b= int(input("Enter second number:"))
GCD= gcd(a,b)
print("GCD is: ")
print(GCD).

Output:-
Enter first number:24
Enter second number:15
GCD is:
3

b. To find the factorial of positive integer


1.Using General Function:-
def factorial(n):
fact= 1
for i in range(1,n):
fact= fact* i
return fact
n= int(input("eneter a number"))
if n> 0:
print(factorial(n))
else:
print("sorry! we cant find factorial for a negative number")

2.Using Recursion:-

def factorial(n):
if n= = 1:
return 1
else:
return n* factorial(n- 1)
n= int(input("eneter a number"))
if n> 0:
print(factorial(n))
else:
print("sorry! we cant find factorial for a negative number")

output:-
enter a number5
120

c Program to display the Fibonacci sequence up to n- th term


1.Using General Function:-
def fib(nterms):
n1, n2 = 0, 1
count= 1
if nterms = = 0:
return n1
elif nterms = = 1:
return n2
else:
while count< nterms:
nth = n1+ n2
n1= n2
n2 = nth
count+= 1
return nth
n= int(input("enter no of terms"))
for i in range(n):
print(fib(i),end= ",")
2.Using Recursion :-
def fib(nterms):
if nterms= = 1:
return 1
elif nterms = = 0:
return 0
else:
return fib(nterms- 1)+fib(nterms- 2)
n= int(input("enter no of terms"))
for i in range(n):
print(fib(i),end= ",")

output:-
enter no of terms8
0,1,1,2,3,5,8,13,

d. To convert decimal number to Binary equivalent


1.Using General Function:-
def binary(num):
bn= ""
while num!= 0:
r= num%2
num= num/ / 2
bn+= str(r)
return bn[ ::- 1]
n= int(input("enter anumber"))
print(binary(n))

output:-
Enter an integer: 5
101
2.Using Recursion
def binary(n):
if n > 1:
binary(n/ / 2)
print(n % 2,end = '')
n= int(input("enter anumber"))
print(binary(n))

output:-
Enter an integer: 5
101

11. Program with a function that accepts two arguments: a list and a
number ‘n’. It
should displayall thenumbers in the list that are greater than the given
number ‘n’.

def big_than_list(l1,n):
l2= [ ]
for item in l1:
if(item> n):
l2.append(item)
return l2
def main():
list1= [ 20,40,88,98,50,23,78,25,67]
num= int(input("enter a number"))
new_list= big_than_list(list1,num)
print(new_list)
if _ _name_ _= = "_ _main_ _":
main()

output:-
enter a number45
[ 88, 98, 50, 78, 67]
12. Program with a function to find how many numbers are divisible by
2, 3,4,5,6 and 7 between 1to 1000

def count_divisible():
for i in range(2,8):
count= 0
for j in range(1,1001):
if(j%i= = 0):
count+= 1
print("no of numbers divisible by ",i ," from (1,1000)are",count)
count_divisible()

output:-
no of numbers divisible by 2 from (1,1000)are 500
no of numbers divisible by 3 from (1,1000)are 333
no of numbers divisible by 4 from (1,1000)are 250
no of numbers divisible by 5 from (1,1000)are 200
no of numbers divisible by 6 from (1,1000)are 166
no of numbers divisible by 7 from (1,1000)are 142

13. Program that accept a string as an argument and return the


number of vowels andconsonants thestring contains.
vowels_list= [ 'a','A','e','E','i','I','o','O','u','U']
def count_str(str1):
vcount= 0
ccount= 0
for ch in str1:
if ch in vowels_list:
vcount+= 1
elif ch> = "a" and ch< = "z":
ccount+= 1
return(vcount,ccount)
def main():
st1= input("enter your string")
vc,cc= count_str(st1)
print("vowelcount= ",vc)
print("Consonantcount= ",cc)
if _ _name_ _= = "_ _main_ _":
main()

output:-
enter your stringwelcome to vaagdevi
vowelcount= 8
Consonantcount= 9

14. Program that accepts two strings S1, S2, and finds whether they are
equal are not.

def compare_str(str1,str2):
if str1= = str2:
print("both the strings are equal")
else:
print("both the strings are not equal")
st1= input("enter 1st string")
st2= input("enter 2nd string")
compare_str(st1,st2)

ouput:-
enter 1st stringhello
enter 2nd stringhello
both the strings are equal

15.Program to count the number of occurrences of characters in a


given string.
str1= input("enter any string")
str2= " "
for ch in str1:
if ch not in str2:
if ch= = " ":
pass
else:
str2+= ch
print(str2)
for ch in str2:
count1= str.count(str1,ch)
print("no of occurrence of ",ch,"= ",count1)

Output:
enter any stringwelcome to vaagdevi degree and pg college
welcomtvagdirnp
no of occurrence of w = 1
no of occurrence of e = 8
no of occurrence of l = 3
no of occurrence of c = 2
no of occurrence of o = 3
no of occurrence of m = 1
no of occurrence of t = 1
no of occurrence of v = 2
no of occurrence of a = 3
no of occurrence of g = 4
no of occurrence of d = 3
no of occurrence of i = 1
no of occurrence of r = 1
no of occurrence of n = 1
no of occurrence of p = 1

16. Program to find whether a given string is palindrome or not


str1= input("enter any string:")
str2= str1[ ::- 1]
print("Given string:",str1)
print("Reverse string:",str2)
if str1= = str2:
print("The given string is palindrome")
else:
print("The given string is not palindrome")

output:-
enter any string:madam
Given string: madam
Reverse string: madam
The given string is palindrome

17. Program with a function that takes two lists L1and L2 containing
integer numbers as parameters. The return value is a single list
containing the pairwise sums of the numbers in L1and L2.

def my_sum(n1,n2):
return n1+ n2
l1= [ 1,2,3,4]
l2= [ 5,6,7,8]
result= map(my_sum,l1,l2)
print(l1)
print(l2)
print(list(result))

output:-
[ 1, 2, 3, 4]
[ 5, 6, 7, 8]
[ 6, 8, 10, 12]
18. Program to read the lists of numbers as L1, print the lists in reverse
order without using reverse function

n= int(input("how many numbers you want to enter in the list:"))


l1= [ ]
for i in range(n):
n1= int(input("enter a number"))
l1.append(n1)
l2= l1[ ::- 1]
print(l1)
print(l2)

output:-
how many numbers you want to enter in the list:4
enter a number10
enter a number20
enter a number30
enter a number40
[ 10, 20, 30, 40]
[ 40, 30, 20, 10]

19. Program to find mean, median, mode for the given set of numbers
in a list.

def mean(l1):
total= sum(l1)
return total/ len(l1)
def median(l1):
l1.sort()
if len(l1) % 2!= 0:
mid_ind= int(len(l1)/ 2)
return l1[ mid_ind]
elif len(l1) % 2= = 0:
mid1= int(len(l1)/ 2)
mid2= int(len(l1)/ 2- 1)
return mean([ l1[ mid1] ,l1[ mid2] ] )
def mode(l1):
max_count= (0,0)
for item in l1:
occurrence= l1.count(item)
if occurrence > max_count[ 0] :
max_count= (occurrence,item)
return max_count
list1= [ 13,13,13,13,14,14,16,18]
print("mean= ",mean(list1))
print("mode= ",mode(list1))
print("median= ",median(list1))

output:-
mean= 14.25
mode= (4, 13)
median= 13.5

20. Program to find all duplicates in the list.

l1= [ 13,13,14,14,14,15,16,2,3]
l2= [ ]
for i in range(len(l1)- 1):
for j in range(i+1,len(l1)):
if l1[ j] not in l2:
if l1[ j] = = l1[ i] :
print(l1[ i] ,"duplicated")
l2.append(l1[ j] )

output:-
13 duplicated
14 duplicated

21. Program to o find all the unique elements of a list.

l1= [ 13,13,14,14,14,15,16,2,3]
l2= [ ]
for item in l1:
if item not in l2:
l2.append(item)
print("unique element list",l2)

output:-
unique element list [ 13, 14, 15, 16, 2, 3]

22. a Program to find max and min of a given tuple of integers.

t= tuple()
n= int(input("Total number of values in tuple"))
for i in range(n):
a= int(input("enter elements"))
t= t+(a,)
print(t)
print ("maximum value= ",max(t))
print ("minimum value= ",min(t))

output:-
Total number of values in tuple5
enter elements10
enter elements200
enter elements30
enter elements40
enter elements60
(10, 200, 30, 40, 60)
maximum value= 200
minimum value= 10

b. Write a program that combine lists L1and L2 into a dictionary.


keys= [ "apples","bananas","custardapple"]
values= [ 20,30,40]
fruits1= {}
for i in range(len(keys)):
for j in range(len(values)):
if i= = j:
fruits1[ keys[ i] ] = values[ j]
break
print(fruits1)
fruits2= {}
fruits2= {keys[ i] :values[ i] for i in range(len(keys))}
print(fruits2)
fruits3= {}
fruits3= dict(zip(keys,values))
print(fruits3)

output:-
{'apples': 20, 'bananas': 30, 'custardapple': 40}
{'apples': 20, 'bananas': 30, 'custardapple': 40}
{'apples': 20, 'bananas': 30, 'custardapple': 40}

23. Program to find union, intersection, difference, symmetric


difference of given two sets.

A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
print("set A:",A)
print("set B:",B)
print("Union :", A | B)
print("Intersection :", A & B)
print("Difference :", A - B)
print("Symmetric difference :", A ^ B)

output:-
set A: {0, 2, 4, 6, 8}
set B: {1, 2, 3, 4, 5}
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}

24. Program to display a list of all unique words in a text file

Vaag.txt
The vaagdevi degree and pg college is one of the college in warangal,
it is 1'st ranked college in Warangal
it is affiliated to kakatiya university Warangal

# open text file in read mode.


text_file = open('vaag.txt', 'r')
# reading all the contents of the file
text = text_file.read()
# cleaning
# Convert text to lower case or upper case.
# We do not want ‘the’ to be different from ‘The’.
text = text.lower()
# Split file contents into list of words.
words = text.split()
# Clean the words that are infested with punctuation marks.
# Something like stripping the words from full- stops, commas, etc.
words = [ word.strip('.,!; ()[ ] ') for word in words]
# finding unique
unique = [ ]
for word in words:
if word not in unique:
unique.append(word)
# sort
unique.sort()
# print
print(unique)
output:-
[ "1'st", 'affiliated', 'and', 'college', 'degree', 'established', 'in', 'is', 'it',
'kakatiya', 'of', 'one', 'pg', 'ranked', 'the', 'to', 'university', 'vaagdevi',
'warangal', 'well']
25. Program to read the content of a text file and display it on the
screen line wise with a line number followed by a colon

file1= open("vaag.txt","r")
k= 1
for each_line in file1:
print(k,":",each_line, end= "")
k= k+1

output:-
1: The vaagdevi degree and pg college is one of the college in warangal,
2 : it is 1'st ranked college in warangal
3 : it is affiliated to kakatiya university Warangal

26. Program to analyze the two text files using set operations

Text1.txt
Vaagdevi Degree and PG college Hanamkonda Warangal
Text2.txt
Vaagdevi Engeneering College Bollikunta Warangal
set1= set()
set2= set()
with open('text1.txt','r') as file:

# reading each line


for line in file:

# reading each word


for word in line.split():

# displaying the words


print("words in 1st file")
print(word)
# adding the words to set1
set1.add(word.lower())
with open('text2.txt','r') as file:

# reading each line


for line in file:

# reading each word


for word in line.split():

# displaying the words


print("words in 2nd file")
print(word)
# adding the words to set1
set2.add(word.lower())
print("common words in two files",set1&set2)
print("all the words in two files",set1|set2)
print("words in 1st file only",set1- set2)

output:- words in 1st file


Vaagdevi
Degree
and
PG
college
Hanamkonda
warangal
words in 2nd file
Vaagdevi
Engeneering
College
Bollikunta
warangal
common words in two files {'vaagdevi', 'college', 'warangal'}
all the words in two files {'engeneering', 'warangal', 'pg', 'hanamkonda',
'vaagdevi', 'and', 'degree', 'bollikunta', 'college'}
words in 1st file only {'pg', 'degree', 'hanamkonda', 'and'}

27. Write a program to print each line of a file in reverse order.


Text3.txt
Vaagdevi Degree and PG college Hanamkonda warangal
Vaagdevi Engeneering College Bollikunta Warangal

Program:-
with open('text3.txt','r') as file:
# reading each line
for line in file:
print(line[ ::- 1] )

output:-
lagnaraw adnokmanaH egelloc GP dna eergeD ivedgaaV
lagnaraw atnukilloB egelloC gnireenegnE ivedgaaV

28. Program to implement different kinds of the inheritance

# program to implement single levlel inheritance


class Base:
def b1(self):
print("base class method")
class Derived(Base):
def d1(self):
print("derived class method")

b= Base()
b.b1()
d= Derived()
d.d1()
d.b1()

output:-
base class method
derived class method
base class method

# program to implement multilevel inheritance

# base class
class Base:
def b1(self):
print("base class method")
class Intermediatry(Base):
def i1(self):
print("intermediatry class method")
class Derived(Intermediatry):
def d1(self):
print("derived class method")

b= Base()
# base class object
b.b1()
# intermediatry class object
i= Intermediatry()
i.i1()
i.b1()
# derived class object
d= Derived()
d.d1()
d.i1()
d.b1()

output:
base class method
base class method
intermediatry class method
derived class method
intermediatry class method
base class method

# program to implement hierarchical inheritance


# base class
class Base:
def b1(self):
print("base class method")
# child class1
class child1(base):
def cc1(self):
print("child class1method")
# child class2
class child2(base):
def cc2(self):
print("child class2 method")
# base class object
b= base()
b.b1()
# child1class object
c1= child1()
c1.b1()
c1.cc1()
# child2 class object
c2= child2()
c2.b1()
c2.cc2()

output:
base class method

base class method


child class1method
base class method
child class2 method

# program to implement Multiple inheritance


# Base Class1
class Base1:
def b1(self):
print("Base Class1Method")
# Base class 2
class Base2():
def b2(self):
print("Base Class2 Method")
# Child Class
class Child(Base1,Base2):
def c1(self):
print("Child Class Method")

# base class1object
p1= Base1()
p1.b1()
# p1.b2()
# p1.c1()

# base class2 object


p2= Base2()
# p2.b1()
p2.b2()
# p2.c1()

# Child class object


c= Child()
c.b1()
c.b2()
c.c1()
output:-
Base Class1Method
Base Class2 Method
Base Class1Method
Base Class2 Method
Child Class Method

# program to implement Hybrid inheritance


# Base Class1
class A:
def m1(self):
print("class A m1method")

class B(A):
def m2(self):
print("class B m2 method")

class C(A):
def m3(self):
print("class C m3 method")

class D(B,C):
def m4(self):
print("class D m4 method")
a= A()
a.m1()
b= B()
b.m1()
b.m2()
c= C()
c.m1()
c.m3()
d= D()
d.m1()
d.m2()
d.m3()
d.m4()

output:-
class A m1method

class A m1method
class B m2 method
class A m1method
class C m3 method

class A m1method
class B m2 method
class C m3 method
class D m4 method

29. Program to implement the polymorphism


Operator overloading:-
# program to implement operator overloading + to add 2 objects
class Product:
def __init__(self,price):
self.price= price
def __add__(self,second):# self= p1second= p2
return self.price+second.price # p1.price+p2.price
# creation of objects
p1= Product(55)
p2 = Product(26)
print("Bill is :",p1+p2)# p1.__add__(p2)

output:-
Bill is : 81

Method Overloading: -
# program to demonstrate method overloading with default values
class Addition:
def add(self,a= 0,b= 0,c= 0):
print("sum is :",(a+b+c))
# creation of object
a= Addition()
a.add()
a.add(4)
a.add(4,5)
a.add(4,5,6)
output:-
sum is : 0
sum is : 4
sum is : 9
sum is : 15

30. Programs to implement Linear search and Binary search


Linear search
list1= [ 17,16,25,31,78,67,45]
print(list1)
key= int(input("enter search element"))
flag= 0
for i in range(len(list1)):
if key= = list1[ i] :
flag= 1
break
if flag= = 1:
print("element found in ",i+1,"th position")
else:
print("element does not found")

output:-
[ 17, 16, 25, 31, 78, 67, 45]
enter search element45
element found in 7 th position
Binary search
a= [ 16,17,25,31,45,67,78]
print(a)
key= int(input("enter search element"))
flag= 0
low= 0
high= len(a)- 1
while low< = high:
mid= int((low+high)/ 2)
if a[ mid] = = key:
flag= 1
break
elif a[ mid] < key:
low= mid+1
continue
elif a[ mid] > key:
high= mid- 1
continue
if flag= = 1:
print("element found in ",mid+1,"th position")
else:
print("element does not found")

output:-
[ 16, 17, 25, 31, 45, 67, 78]
enter search element67
element found in 6 th position

31. Programs to implement Selection sort, Insertion sort

# program to sort the elements in the list using selectionsort


def selection_sort(a):
for x in range(0,len(a)):
imin= x
for y in range(x+1,len(a)):
if(a[ imin] > a[ y] ):
imin= y
a[ x] ,a[ imin] = a[ imin] ,a[ x]
list1= [ 2,9,4,1,3]
print("list before sorting")
print(list1)
selection_sort(list1)
print("list after sorting")
print(list1)

output:-
[ 1,2,3,4,9]
Insertionsort

# program to sort the elements in the list using insertion sort


def insertion_sort(a):
for i in range(1,len(a)):
b= a[ i]
j= i
while j> 0 and a[ j- 1] > b:
a[ j] = a[ j- 1]
j= j- 1
a[ j] = b
list1= [ 2,9,4,1,3]
print("list before sorting")
print(list1)
insertion_sort(list1)
print("list after sorting")
print(list1)

output:-
[ 1,2,3,4,9]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy