0% found this document useful (0 votes)
5 views

Deepak python practical file

This document is a practical file for a Python course at Shri Guru Ram Rai University, detailing various programming exercises. It includes programs on strings, loops, lists, sets, dictionaries, functions, and SQLite, with specific tasks and sample code provided. The file is submitted by a student and reviewed by an assistant professor.

Uploaded by

dccreator9068
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)
5 views

Deepak python practical file

This document is a practical file for a Python course at Shri Guru Ram Rai University, detailing various programming exercises. It includes programs on strings, loops, lists, sets, dictionaries, functions, and SQLite, with specific tasks and sample code provided. The file is submitted by a student and reviewed by an assistant professor.

Uploaded by

dccreator9068
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/ 45

SHRI GURU RAM RAI UNIVERSITY

PRACTICAL FILE
Subject Code-BS-DSE5.4
Name of Subject- PYTHON

Course :- Bsc.it
Semester :-6th
(School of CA & IT)

Submitted by:- Submitted to:-


Deepak Singh Mr.GD Makkar
Enroll no:-R190530016 Assistant Professor
S. No. Programs Page No.

1. Programs on string 1

2. Programs on For loop 13

3. Program on Lists 16

4. Programs on Sets 23

5. Programs on Dictionary 26

6. Programs on Functions 30

7. Programs on Lambda and Map 33


function
8. Programs on sorting techniques 36

9. Programs on Sqlite 39
PROGRAMS ON STRING

Q.1 Write a python program to calculate the length of a string.


Ans. a=input(“enter the string: ”)
Print(“The length of the given string is: “, len(a))
O/P:

Q.2 Write a python program to count the number of character


(character frequency) in a string.
Ans. x=input(“enter the string; “)
res= { }
for i in x:
res[i]=res.get(i,0)+1
print(“frequency of each characters’\n”, res)
O/P:

Q.3 Write a python program to get a string made of the first 2 and
the last 2 characters from a given string. If the string is less than 2,
return instead of the empty string.
Ans a=input(“enter the string: ”)
If len(a)>=2
x=a[0:2]
y=a[len(a)-2:len(a)]
print("the string made of the first and last two character of the
given string:",x+y)
else:
print(“ “)
O/P:
Q.4 Write a python program to get a string from a given string where
all occurrence of its first character have been changed to ‘$’ except
the first character listed.
Ans x=input(“enter the string: ”)
char=x[0]
x=x.replace(char, ‘$’)
x=char+x[1:]
print(x)
O/P:

Q.5 Write a python program to get a single string from two given
strings, separated by a space and swap their first two characters.
Ans x=input(“enter the first string: “)
y=input(“enter the second string: “)
a=y[:2]+x[2:]
b=x[:2]+y[2:]
print(a+” “+b)

O/P:
Q.6 Write a python program to add ‘ing’ at the end of the string
(length should be at least 3). If the given string already ends with
‘ing’ then add ‘ly’ instead. If the string length pf the given string is
less than 3, leave it unchanged.
Ans x=input(“enter the string: “)
if len(a)>=3:
if “ing” not in a:
print(a+”ing”)
else:
print(a+”ly”)
else:
print(a)
O/P:

Q.7 Write a python program to find the first appearance of the


substring “not” and “poor” from a given string, if ‘not’ follows the
‘poor’, replace the whole ‘not’……’poor’ substring with “good”.
Return the resulting string.
Ans x=input(“enter the string: ”)
snot=x.find(“not”)
spoor=x.find(“poor”)
if spoor>snot and snot>0 and spoor>0:
x=x.replace(x[snot:(spoor+4)], ‘good’)
print(x)
else:
print(x)

O/P:
Q.8 Write a python program that takes a list of words and returns
the length of the longest one.
Ans a=input(“enter the list of the string: ”)
n=a.split()
lo=len(n[0])
for i in n:
if(len(i)>lo):
lo=len(i)
print(“the length of the longest word is: “, lo)
O/P:

Q.9 Write a python program to remove the nth index character from
a non-empty string.
Ans a=input(“enter the string: “)
n=int(input(“enter the index no. which is to be remove “)
x=a[:n]
y=a[n+1:]
print(x+y)
O/P:

Q.10 Write a python program to reverse a string if its length is a


multiple of 4.
Ans a=input(“enter the string: “)
if len(a)%4==0:
print(‘’.join(reversed(a)))
else:
print(“The length is not the multiple of 4”)
O/P:
Q.11 Write a python program to convert a given string to all
uppercase if it contains at least 2 uppercase characters in the first 4
character.
Ans x=input(“enter the string: “)
a=0
for i in x[:4]:
if i.upper()==i:
a+=1
if a>=2:
print(x.upper())
else:
print(x)
O/P:

Q.12 Write a python program to check whether a string starts with


specified characters.
Ans x=input(“enter the string: “)
n=int(input(“enter the value you want to check “)
y=x.startswith(“n”)
O/P:
Q.13 Write a python program to display a number in left, right and
center aligned at width 10.
Ans x=input(“enter the string: “)
y=x.center(10)
print(y)

O/P:

y=x.ljust(10)
print(y)

O/P:

y=x.rjust(10)
print(y)

O/P:

Q.14 Write a python program to reverse a string.


Ans x=input(“enter the string: “)
y=x[::-1]
print(y)
O/P:
Q.15 Write a python program to reverse words in a string.
Ans x=input(“enter the sentence: “)
for line in x.split(‘\n’)
reverse=’’.join(line.split()[::-1])
print(reverse)
O/P:

Q.16 Write a python program to count repeated characters in a


string.
Ans x=input(“enter the string: “)
f={ }
for i in x:
if i in f:
f[i]+=1
else:
f[i]=1
for k in f:
if f[k]>1
print(k, f[k])
O/P:
Q.17 Write a python program to if a string contains all letters of the
alphabet.
Ans import string
alpha=set(string.ascii_lowercase)
x=input(“enter the string: “)
print(set(x.lower())>=alpha)
O/P:

Q.18 Write a python program to count and display the vowels of a


given text.
Ans x=input(“enter the string: “)
vowels=”aeiouAEIOU”
print(len([letter for letter in x if letter in vowels]))
print([letter for letter in x if letter in vowels])

O/P:
Q.19 Write a python program to find the first non-repeating
character in a given string.
Ans def func(x)
c=[ ]
f={ }
for i in x:
if i in f:
f[i]+=1
else:
f[i]=1
c,append(i)
for i in c:
if f[i]==1
return(i)
return(“none”)
x=input(“enter the string: “)
func(x)

O/P:

Q.20 Write a python program to remove spaces from a given string.


Ans x=input(“enter the string: “)
x=x.replace(‘ ‘,’’)
print(x)
O/P:
Q.21 Write a python program to capitalize first and last letters of
each word of a given string.
Ans x=input(“enter the string: “)
x=x[0:1].upper()+x[1:len(x)-1]+x[len(x)-1:len(x)].upper()
print(x)

O/P:

Q.22 Write a python program to create a string from two given string
concatenating uncommon characters of the said string.
Ans x=input(“enter the first string: “)
y=input(“enter the second string: “)
set1=set(x)
set2=set(y)
common_chars=list(set1&set2)
result=[ch for ch in x if ch not in common_chars]+ [ch for ch in y if ch
not in common_chars]
print(‘’,join(result))

O/P:
Q.23 Write a python program to count uppercase, lowercase, special
characters and numeric characters in a given string.
Ans x=input(“enter the string: “)
Upper, lower, special, numeric=0, 0, 0, 0
for i in x:
if i>=’A’ and i<=’Z’
upper+=1
elif i>=’a’ and i<=’z’
lower+=1
elif i>=’0’ and i<=’9’
numeric+=1
else:
special+=1
print(“uppercase characters: ” +str(upper))
print(“lowercase characters: ” +str(lower))
print(“numeric characters: “ +str(numeric))
print(“special characters: “ +str(special))
O/P:

Q.24 Write a python program to swap cases of the given string.


Ans x=input(“enter the string: “)
txt=x.swapcase()
print(txt)

O/P:
Programs on For loop

Q.1. WAP to find the sum of a number.


Ans: n=int(input("Enter a number:"))
total=0
while(n>0):
digit=n%10
total=total+digit
n=n//10
print("The total sum of digits is:",total)

O/P

Q.2. WAP to print the table from 1 to 10 in the following


format:

Ans: for i in range(1, 10+1):


for j in range(i, (i*10)+1, i):
print(j, end="\t")
print()

O/P:
Q.3. Write a program to determine whether a given natural
number is a perfect number. A natural number is said to be
perfect number if it is the sum of its devisors. For example, 6
is a perfect number because 6=1+2+3, but 15 is not a perfect
number because 15 ≠ 1+3+5
Ans: n = int(input("Enter any number: "))
sum = 0
for i in range(1, n):
if(n % i == 0):
sum = sum + i
if (sum == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

O/P:

Q.4. WAP that return True or False depending on whether the


given number is a palindrome. A palindromic number is a
number (such as 16461) that remains the same when its
digits are reversed.
Ans: n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
digit=n%10
rev=rev*10+digit
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
O/P:

Q.5. WAP that prints Armstrong numbers in the range 1 to 1000.


An Armstrong number is a number whose sum of the cubes of
the digits is equal to the number itself. For example, 370=33 +
73+ 03.
Ans: num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

O/P:
Program on Lists

Q.1 Write a python program to get the largest and second largest
number from a list.
Ans x=[‘21’, ‘11’, ‘15’, ‘51’]
y=max(x)
print(“the largest no. is”,y)
x.remove(y)
z=max(x)
print(“the second largest no, is “, z)
O/P:

Q.2 Write a python program to remove duplicates from a list.


Ans lst=['ab', 'bc', 'cd', 'ef', 'ab']
dup=set()
uniq=[]
for x in lst:
if x not in dup:
uniq.append(x)
dup.append(x)
print(dup)
O/P:

Q.3 Write a python program to count the number of strings where


the string length is 2 or more and the first and the last characters are
same from a given list of string.
Ans lst=[‘abc’, ‘xyz’, ‘aba’, ‘1221’]
Ctr=0
for word in lst:
If len(word)>1 and word[0]==word[-1]”
ctr+=1
O/P:
Q.4 Write a python program to get the difference between the two
strings.
Ans lst1=['21', '15', '17', '35']
lst2=['23', '14', '21', '11', '15']
diff12=list(set(lst1)-set(lst2))
diff21=list(set(lst2)-set(lst1))
print(diff12+diff21)

O/P:

Q.5 Write a python program to convert a list of characters into a


string.
Ans lst=[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
x=””.join(lst)
print(x)

O/P:

Q.6 Write a python program to find the index of an item in a


specified set.
Ans lst=['21', '15', '17', '35']
lst.index(‘35’)

O/P:

Q.7 Write a python program to append a list to the second list.


Ans lst1=['21', '15', '17', '35']
lst2=['23', '14', '21', '11', '15']
append=lst1+lst2
print(append)

O/P:
Q.8 Write a python program to get unique values from a list.
Ans lst=[‘13’, ‘15’, ‘17’, ‘34’, ‘11’, ‘15’, ‘17’]
my_set=set(lst)
my_newlist=list(my_set)
print(my_newlist)

O/P:

Q.9 Write a python program to get the frequency of the elements in


a list.
Ans mylist=['23', '14', '21', '11', '15', '23', '11']
res={}
for I in mylist:
if (I in res):
res[i]+=1
else:
res[i]=1
for key, value in res.items():
print(key,”:“,value)

O/P:
Q.10 Write a python program to check whether a list contains a
sublist.
Ans lst=['23', '14', '21', '11', '15', '23', '11']
sub=['23', '14', '21']
sub_set=False
if sub==[]:
sub_set=True
elif sub==1:
sub_set=True
elif len(sub)>len(lst):
sub_set=True
else:
for i in range(len(lst)):
if lst[i]==sub[0]:
n=1
while(n<len(sub)) and (lst[i+n]==sub[n]):
n+=1
if n==len(sub):
sub_set=True
print(sub_set)

O/P:

Q.11 Write a python program to find common items from the two
lists.
Ans color1=[“Red”, “Blue”, “Pink”, “Green”]
color2=[“Yellow”, “White”, “Blue”, “Red”]
print(set(color1) & set(color2))

O/P:
Q.12 Write a python program to convert a list of multiple integers
into a single string.
Ans mylist=['23', '14', '21', '11', '15', '23', '11']
y=””.join(mylist)
print(y)

O/P:

Q.13 Write a python program to replace last element in a list with


another element.
Ans lst1=['1', '3', '5', '7', '9', '10']
lst2=['2', '4', '6', '8']
y=lst1.remove(lst1[-1])
new_list=lst1+lst2
print(new_list)

O/P:

Q.14 Write a python program to find the list in a list whose sum of
the elements is the highest.
Ans num=[[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]
print(max(num, key=sum))

O/P:
Q.15 Write a python program to remove duplicates from a list of
lists.
Ans num=[[‘10’, ‘20’],[‘40’], [‘30’, ‘56’, ‘25’], [‘10’, ‘20’], [‘33’], [‘40’]]
new_num=[]
for elem in num:
if elem not in new-num:
new_num.append(elem)
num=new_num
print(new_num)

O/P:

Q.16 Write a python program to flatten the given nested list


structure.
Ans lst=['0', '10', ['20', '30'], '40','50', ['60', '70', '80'], ['90','100', '110',
'120']]
output=[]
def removenestings(lst):
for i in lst:
if type(i)==list:
removenestings(i)
else:
output.append(i)
print("the original list: ", lst)
removenestings(lst)
print("the flatten list after removing nesting: ", output)

O/P:
Q.17 write a python program to remove consecutive duplicates of a
given list.
Ans lis=[‘0’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘4’, ‘5’, ‘6’, ‘6’, ‘7’, ‘8’, ‘9’, ‘4’, ‘4’]
i=0
while i<len(lis)-1:
if lis[i]==lis[i+1]:
del lis[i]
else:
i+=1
print(lis)

O/P:

Q.18 Write a python program to remove the Kth element from a


given list, print the new list.
Ans lis=[‘1’, ‘1’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
k=4
result=lis[:k-1] + lis[k:]
print(result)

O/P:
Programs on Sets

Q.1 Write a python program to add members in a set and iterate


over it.
Ans num_set=set(['0', '1', '2', '3', '4'])
num_set.update(['python', 'anaconda', 'jupyter'])
for n in num_set:
print(n, end=' ')

O/P:

Q.2 Write a python program to item from a set of if it is present in


the set.
Ans vowels={'a', 'e', 'i', 'o', 'u'}
vowels.remove('a')
print(vowels)

O/P:

Q.3 Write a python program to apply union , intersection, difference,


symmetric difference operators on set.
Ans for union:
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n|m
print(“the union of two sets is: “, nm)

for intersection
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n&m
print(“the intersection of two sets is: “, nm)
for difference:
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n-m
print(“the difference of the two sets is: “, nm)
for symmetric_difference:
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n^m
print(“the symmetric difference of the two sets is: “, nm)

Q.4 Write a python program to check if a set is a subset of another


set.
Ans n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
if n.issubset(m):
print("yes the first set is the subset of second set")
else:
print("no the first set is not the subset of second set")

O/P:

Q.5 Write the python program to clear a set.


Ans my_set={'a', 'b', 'c', 'd', 'e'}
my_set.clear()
print(my_set)

O/P:
Q.6 Write a python program to check if two given sets have no
elements in common.
Ans n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
if n.isdisjoint(m):
print("no in the two sets none of the elements are
common")
else:
print("yes in the two sets some of the elements are
common")

O/P:

Q.7 Write a python program to remove intersection of a second list


from the first set.
Ans n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
n.difference_update(m)
print("the first set is ", n)
print("the second set is ", m)

O/P:
Program on Dictionary

Q.1 write a python program to add a key to a dictionary.


Ans my_dict={0:10, 1:20}
my_dict[2]=30
print(my_dict)

O/P:

Q.2 Write a python program to concatenate dictionaries to create


new dictionary.
Ans dict1={1:10, 2:20}
dict2={3:30, 4:40}
dict3={5:50, 6:60}
dict1.update(dict2)
dict1.update(dict3)
print(dict1)

O/P:

Q.3 Write a python program to check whether a given key already


exists in a dictionary.
Ans my_dict={1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
x=int(input("enter the key you want to check"))
if x in my_dict:
print("key is present in the dictionary")
else:
print("key is not present in the dictionary")

O/P:
Q.4 Write a python program to generate and print a dictionary that
contains a number(between 1 and n) in the form (x, x*x).
Ans n=int(input("enter the no. "))
d=dict()
for x in range(1, n+1):
d[x]=x*x
print(d)

O/P:

Q.5 Write a python program to print a dictionary where the keys are
numbers between 1 and 15(both included) and the values are the
squares of keys.
Ans d=dict()
for x in range(1, 16):
d[x]=x*x
print(d)
O/P:

Q.6 Write a python program to merge two python dictionaries.


Ans d1={1:'Jan', 2:'Feb'}
d2={3:'Mar', 4:'Apr'}
d1.update(d2)
print(d1)

O/P:
Q.7 Write a python program to sum and multiply all the items in a
dictionary.
Ans my_dict={'data1': 100, 'data2': 200, 'data3':300}
print(sum(my_dict.values()))

O/P:

my_dict={'data1': 100, 'data2': 200, 'data3':300}


result=1
for key in my_dict:
result=result*my_dict[key]
print(result)

O/P:

Q.8 Write a python program to sort a dictionary by key.


Ans my_dict={'data2': 100, 'data3': 200, 'data1':300}
print(sorted(my_dict.keys()))

O/P:

Q.9 Write a python program to remove the duplicate values from


dictionary.
Ans my_dict={'data2': 100, 'data3': 200, 'data1':300, 'data4':100}
uniq=dict()
for key, value in my_dict.items():
if value not in uniq.values():
uniq[key]=value
print(uniq)

O/P:
Q.10 Write a python program to combine two dictionary adding
values for common keys.
Ans my_dict1={'data2': 100, 'data3': 200, 'data1':100, 'data4':100}
my_dict2={'data2': 100, 'data1': 200, 'data3':300}
for i in my_dict2:
if i in my_dict1:
my_dict1[i]=my_dict1[i]+my_dict2[i]
else:
my_dict1[i]=my_dict2[i]
print(my_dict1)

O/P:

Q.11 Write a python program to find the highest 3 values in a


dictionary.
Ans my_dict1={'data2': 100, 'data1': 200, 'data3':300, 'data4':500}
dict1=sorted(my_dict1.values())
largest_no=dict1[-1]
second_largest_no=dict1[-2]
third_largest_no=dict1[-3]
print("the three highest values are", largest_no," ",
second_largest_no, " ", third_largest_no)

O/P:

Q.12 Write a python program to filter a dictionary based on values.


Ans my_dict={'data2': 100, 'data1': 200, 'data3':300, 'data4':500}
result={key:value for (key, value) in my_dict.items() if value>=250}
print("data greater than 250", result)

O/P:
Program on Functions

Q.1 Write a python function to sum all the numbers in a list.


Ans lst=[1, 3, 4, 6, 11, 12]
def list_sum(lst):
add_items=sum(lst)
return add_items
print("the sum of all the no. of the list is", list_sum(lst))

O/P:

Q.2 Write a python function to reverse a string.


Ans str1=input("enter the string:")
def reverse(str1):
return str1[::-1]
print("the reverse of the said string is: ", reverse(str1))
O/P:

Q.3 Write a python function to calculate the factorial of a number(a


non-negative integer). The function accepts the number as an
argument.
Ans def factorial(x):
if x==1:
return 1
else:
fact=x*factorial(x-1)
return(fact)
n=int(input("enter the no. "))
print("the factorial of the given no. is ", factorial(n))
O/P:
Q.4 Write a python function that accepts a string and calculate the
number of uppercase letters and lowercase letters.
Ans str1=input("enter the string:")
def upper_letters(x):
upper=0
for i in x:
if i>='A' and i<='Z':
upper+=1
return upper
def lower_letters(x):
lower=0
for i in x:
if i>='a' and i<='z':
lower+=1
return lower
print("the no. of uppercase letters in the string:
",upper_letters(str1))
print("the no. of lowercase letters in the string: ",
lower_letters(str1))
O/P:

Q.5 Write a python function to check whether the number is perfect


or not.
Ans n=int(input("enter the no."))
def perfect_no(x):
sum=0
for i in range(1, x):
if x%i==0:
sum+=i
return sum==x
print(perfect_no(n))
O/P:
Q.6 Write a python function to check whether a string is a pangram
or not.
Ans import string
def ispangram(str1):
alpha=set(string.ascii_lowercase)
return alpha<=set(x.lower())
x=input("enter the string: ")
print(ispangram(x))
O/P:
Programs on Lambda and Map Function

Q.1 Write a python program to square and cube every number in a


given list of integers using lambda.
Ans lst=[2, 4, 6, 8, 9]
y=map(lambda x:x**2, lst)
z=map(lambda x:x**3, lst)
print("The square of the no. in the list: ", list(y))
print("The cube of the no. in the list: ", list(z))

O/P:

Q.2 Write a python program to find if a given string starts with a


given character using lambda.
Ans str1=input("enter the string: ")
c=input("enter the character you want to check ")
z=(lambda x,e:True if x.startswith(e) else False)
print(z(str1, c))

O/P:
Q.3 Write a python program to count the even, odd numbers in a
given array of integers using lambda.
Ans lst=[2, 4, 6, 8, 9, 11, 15]
print("the original list is ", lst)
odd_ctr=len(list(filter(lambda x:(x%2!=0), lst)))
even_ctr=len(list(filter(lambda x:(x%2==0), lst)))
print("the no. of even numbers in the list is ", even_ctr)
print("the no. of odd numbers in the list is ", odd_ctr)
O/P:

Q.4 Write a python program to add two given lists using map and
lambda.
Ans lst1=[2, 4, 6, 8, 9, 11, 15]
lst2=[3, 6, 7, 8, 3, 2, 1]
print("the first list is: ", lst1)
print("the second list is: ", lst2)
add_list=map(lambda x, y:x+y, lst1, lst2)
print("the sum of the two given lists are ", list(add_list))
O/P:

Q.5 Write a python program to calculate the sum of the positive and
negative numbers of a given list of numbers using lambda function.
Ans lst1=[-2, 4, -6, 8, 19, 10, -1]
lst2=[3, -6, 4, -8, -3, -2, 1]
print("the first list is: ", lst1)
print("the second list is: ", lst2)
add_list=map(lambda x, y:x+y, lst1, lst2)
print("the sum of the two given lists are ", list(add_list))
O/P:

Q.6 Write a python program to convert all the characters in


uppercase and lowercase and eliminate duplicate letters from a
given sequence. Use map function().
Ans def change_cases(s):
return str(s).upper(), str(s).lower()
str1=('a', 'b', 'I', 'U', 'c', 'E', 'a', 'E')
print("the original sequence is ", str1)
result=map(change_cases, str1)
print("the sequences after changing the cases and eliminating
duplicate values:\n")
print(set(result))
O/P:
Program on Sorting Techniques

Q.1 Write a python program to sort a list of elements using the


bubble sort algorithm.
Ans: a=[16,19,11,15,10,12,14]
print("the original list ",a)
for j in range(len(a)):
swapped=False
i=0
while i<len(a)-1:
if a[i]>a[i+1]:
a[i],a[i+1]=a[i+1],a[i]
swapped=True
i=i+1
if swapped==False:
break
print("the sorted list using bubble sort ", a)

O/P:

Q.2 Write a python program to sort a list of elements using the


selection sort algorithm.
Ans: a=[18,10,11,15,60,56,14]
print("the original list ",a)
i=0
while i<len(a):
smallest=min(a[i:])
index_of_smallest=a.index(smallest)
a[i],a[index_of_smallest]=a[index_of_smallest],a[i]
i=i+1
print("the sorted list using selection sort ", a)
O/P
Q.3 Write a python program to sort a list of elements using the
insertion sort algorithm.
Ans: a=[12,15,6,16,10,25,17]
print("the original list ",a)
for i in a:
j = a.index(i)
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print("the sorted list using insertion sort ", a)
O/P:

Q.4 Write a python program to sort a list of elements using the linear
search algorithm.
Ans: lst = []
num = int(input("Enter size of list :- "))
for n in range(num):
numbers = int(input("Enter the array of %d element :- "
%n))
lst.append(numbers)
x = int(input("Enter number to search in list :- "))
i=0
flag = False
for i in range(len(lst)):
if lst[i] == x:
flag = True
break
if flag == 1:
print('{} was found at index {}.'.format(x, i))
else:
print('{} was not found.'.format(x))

O/P:

Q.5 Write a python program to sort a list of elements using the


binary search algorithm.
Ans def binarySearch (arr, l, r, x):
if r >= l:
mid = l + (r - l)//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid+1, r, x)
else:
return -1
xlist = input('Enter the sorted list of numbers: ')
xlist = xlist.split()
xlist = [int(x) for x in xlist]
key = int(input('The number to search for: '))
result = binarySearch(xlist, 0, len(xlist)-1, key)
if result != -1:
print('{} was found at index {}.'.format(key, result))
else:
print('{} was not found.'.format(key))

O/P:
Program on Sqlite

Doctor
HOSPITAL

Hospital_Id(P) Doctor_Id(P)
Hospital_Name Doctor_Name
Bed_count Hospital_Id(F)
Joining_Date
Speciality
Salary
Experience

WAP to perform the following queries:


Q.1. Create tables Hospital and Doctor.
Ans. import sqlite3
conn=sqlite3.connect('mydatabase.db')
cr=conn.cursor()
cr.execute("create table HOSPITAL(Hospital_Id integer not null
Primary key ,Hospital_Name Text not null,Bed_count integer not
null)");
conn.commit()
print("HOSPITAL is created")

O/P:

import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
cr.execute("create table DOCTOR(Doctor_id integer Primary key
,Doctor_Name Text not null, Hospital_id integer not null,
Speciality text not null, salary integer not null, Experience
integer)");
conn.commit()
print("TABLE DOCTOR is created")

O/P:

Q.2. Insert records in tables hospital and Doctor by taking input from
user.
Ans. import sqlite3
conn=sqlite3.connect('manisha.db')
cr=conn.cursor()
Hospital_id=int(input("Enter Hospital_id: "))
HOspital_name=input("Enter Name Of The Hospital: ")
Bed_count=int(input("Enter Bed count: "))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
conn.commit()

O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
Doctor_id=int(input("Enter doctor_id: "))
Doctor_name=input("Enter Name Of The Doctor: ")
Hospital_id=int(input("Enter Hospital_id: "))
Speciality=input("enter speciality: ")
Experience=int(input("Experience: "))
salary=int(input("salary: "))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
conn.commit()

O/P:
Q.3 Fetch the information of the tables Hospital and Doctor.

Ans. import sqlite3

conn=sqlite3.connect('mydb.db')

cr=conn.cursor()

cr.execute("select* from DOCTOR")

rows=cr.fetchall()

for row in rows:

print(row)

conn.commit()

O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
cr.execute("select* from HOSPITAL")
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()
O/P:

Q.4. Get the list of doctors as per the given speciality and salary.
Fetch all doctors whose salary is higher than the input amount and
speciality is the same as the input speciality.
Ans. import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
n=int(input("enter the input salary: "))
cr.execute("select Doctor_name from DOCTOR where salary >
%d"%n)
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()

O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
n=input("enter the speciality ")
cr.execute("select Doctor_name from DOCTOR where
Speciality=='%s'" %n)
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()

O/P:

You might also like